	********************************************************************************
	**** Date: 6.25.2020				****
	**** Update: 2.20.2023				****
	**** Author: JW josephgwright@gmail.com 				****	
	** NOTE: This program has been executed in Stata 17	****

	**** 	Using files in $dir:		****
	
 *** btscs.ado
 *** GWFglobal2020.dta
 *** Personalist-Parties-Final.xlsx
 *** prio-mergeB.dta
 *** qog2020.dta
 *** reign-regime.csv
 *** Sigman_MinisterData_forIRT.dta
 *** statecapacity_merge.dta
 *** V-Dem-CPD-Party-V1.dta
 *** V-Dem-CY-Full+Others-v111.dta
 *** wdi-merge.dta
 *** WhoGov_within_V2.0.xlsx
 *** world-bank-statistical-capacity-indicators.csv

	***********************************************************************************
	**** Additional modules and packages required for executing the following code ****
	***********************************************************************************
		** ciplot.ado
		** estout.ado
		** ivreg2.ado	
		** krls.ado
		** listtex.ado
		** reghdfe.ado
		** sutex.ado
		** xtivreg2.ado
		** fect.ado
		** ife.ado

	******************************
	**** Set directory, seed *****
	******************************
		capture log close
		log using PersParty.log, replace
		set more off 
		set matsize 1000
		global seed ="984353"
		set scheme plotplain
		global dir = "C:\Users\jgw12\OneDrive - The Pennsylvania State University\Desktop\Li-Wright-CPS-Reproduction" /* set folder for .pdfs */
		cd "C:\Users\jgw12\OneDrive - The Pennsylvania State University\Desktop\Li-Wright-CPS-Reproduction"  /* set folder for data */

		* VDem data * /* downloaded 4.06.2020 from https://www.v-dem.net/en/data/data/v-dem-dataset-v111/ */
			use V-Dem-CY-Full+Others-v111,clear
			keep if year>=1900
			keep country_name year COWcode v2x_polyarchy v2x_libdem v2x_partipdem v2x_freexp_altinf v2x_frassoc_thick ///
				v2x_clpol v2x_civlib v2x_clphy  v2x_jucon v2juhcind v2x_ex_confidence v2xlg_legcon v2dlencmps v2cltort v2clkill v2x_corr ///
				e_civil_war e_migdppcln e_migdpgro e_wbgi_gee e_wbgi_pve e_v2xel_frefair_3C e_v2xcl_rol_3C ///
				v2xel_elecpres v2xel_elecparl v2xps_party v2x_regime v2exl_legitlead* v2cacamps* v2smpolsoc* ///
				v2stfisccap v2clrspct*  v2stcritrecadm*  v2stcritapparm v2strenadm*  v2strenarm v2peasbepol v2peasjpol ///
				v3stcensus v3stnatbank v3ststatag v3ststybcov v3ststybpub v3stnatant v3stflag v2svstterr v2cltrnslw*  ///
				v2x_pubcorr v2x_execorr v2xnp_regcorr  e_v2x_pub* v2excrptps v2exthftps v2elloeldm v2ellostsl v2exl_legit*
			rename country_name vdem_country
			rename COWcode cowcode
			recode cow (679=678) if year>1990
			tab vdem_country if cow==.
			drop if cow==.
			tab vdem_country if cowcode==99999   /* cases in our sample */
			drop if cowcode==99999
			replace v2x_clphy= (v2x_clphy*-1) +1/* flip scale so it measures repression instead of human rights respect */
			*** State bureaucratic capacity index ***
				* Flip corruption so higher value means MORE state capacity and logit transform for linear model *
			replace  v2x_pubcorr=logit((v2x_pubcorr*-1)+1)
			global capvar = "v2clrspct v2stcritrecadm v2strenadm v2x_pubcorr v2cltrnslw"
			sum $capvar
			factor $capvar
			rotate, promax(1)
			gsem  (PER->  $capvar,fam(gaussian)link(id) ///
				var(PER@1)vce(cluster cowcode)) 
			predict vburcap,ebmeans latent se(se_vburcap)
			gen disc=.
			gen diff=.
			gen n=_n
			gen var="v2clrspct" if n==1
			local var ="$capvar"
			local i =1
			foreach v of local var {
				replace var ="`v'" if n==`i'
				replace diff = -_b[`v':_cons] / _b[`v':PER] if n==`i'
				replace disc =  _b[`v':PER] if n==`i'
				local i = `i'+1
			}
			list var disc diff in 1/5,clean noobs
			* drop remuneration from test *
			gsem  (PER->v2clrspct v2stcritrecadm v2x_pubcorr v2cltrnslw,fam(gaussian)link(id) ///
				var(PER@1)vce(cluster cowcode)) 
			predict vburcap4,ebmeans latent 
			  * group latent estimates *
			gsem  (PER->$capvar,fam(gaussian)link(id)var(PER@1)group(v2x_regime))
			predict reg_vburcap,latent ebmeans
			gen coldwar = year<=1989
			replace coldwar=2 if year<1946
			gsem  (PER->$capvar,fam(gaussian)link(id)var(PER@1)group(coldwar))
			predict cw_vburcap,latent ebmeans	
			gen eur=cowcode>=200 & cowcode<400
			gsem  (PER->$capvar,fam(gaussian)link(id)var(PER@1)group(eur))
			predict eur_vburcap,latent ebmeans	
			gen afr=cowcode>=400 & cowcode<=625
			gsem  (PER->$capvar,fam(gaussian)link(id)var(PER@1)group(afr))
			predict afr_vburcap,latent ebmeans	
			gen hipinst = v2xps_party>-.54 if v2xps_party~=.
			gsem  (PER->$capvar,fam(gaussian)link(id)var(PER@1)group(hipinst))
			predict pinst_vburcap
			gsem  (PER->v2clrspct v2strenadm v2stcritrecadm v2x_pubcorr v2cltrnslw,fam(gaussian)link(id) ///
				var(PER@1)vce(cluster cowcode)cov(e.v2stcritrecadm*e.v2strenadm e.v2cltrnslw*e.v2strenadm))
			predict cov_vburcap
			corr vburcap reg_ cw_ eur_ afr_ pinst_ cov_vburcap
			drop reg_ cw_ eur_ afr_ pinst_ 
			
			twoway (lpoly vburcap year if vdem_country=="Turkey"==1  & year>=1982,bw(.5)) ///
				(lpoly vburcap year if vdem_country=="Hungary"==1  & year>=1990,bw(.5) ///
				xtit(Year)legend(lab(1 "Turkey")lab(2 "Hungary")pos(6)col(2)) ///
				ytit(State bureaucratic capacity))
			gr export "$dir\golden\turkey-hungary.pdf",as(pdf)replace 

			*** Access to state jobs/contracts ***
			alpha v2peasbepol v2peasjpol,item std gen(vaccess)
			*** Appointments and renumeration of armed forces ***
			alpha v2strenarm v2stcritapparm,item std gen(vmilitary)
			*** Legibility ***
			egen meancensus =mean(v3stcensus),by(cowcode)
			factor meancensus v3stnatbank v3stnatant v3stflag v3ststatag v3ststybcov v3ststybpub
			alpha meancensus v3stnatbank v3stnatant v3stflag v3ststatag v3ststybcov v3ststybpub,item std gen(v2legibility)
			gsem (PER->meancensus v3stnatbank v3stnatant v3stflag v3ststatag v3ststybcov v3ststybpub,regress var(PER@1))			
			predict vlegibility,ebmeans latent
			pwcorr  v2legibility vlegibility year
			gen vfiscal = v2stfisccap
			gen vterritory=v2svstterr
	 		 
			xtset cowcode year
			gen polarization =l.v2cacamps_ord==4

			*****************************************
			tsset cow year
			sort cowcode year
 			bysort cowcode: replace v2ellostsl=l.v2ellostsl if v2ellostsl==.
			local var = "vburcap vburcap4 cov_vburcap vaccess vmilitary vlegibility vfiscal vterritory v2xps_party v2x_clpol v2x_clphy v2x_civlib v2x_jucon v2juhcind v2x_libdem v2x_partipdem v2x_polyarchy  v2xlg_legcon v2clrspct v2stfisccap  v2stcritrecadm v2stcritapparm v2strenadm v2strenarm v2peasjpol v2peasbepol v2x_pubcorr v2x_execorr v2xnp_regcorr v2cltrnslw v2ellostsl v2exl_legitlead v2exl_legitperf v2exl_legitratio v2exl_legitideol"
			foreach v of local var {
				tsset cow year
				tssmooth ma l1`v'=`v',window(1 0 0)
				tssmooth ma l12`v'=`v',window(2 0 0)
				gen l2`v'=l.l1`v' 
			}
			tsset cow year
			forval i=3/8 {
				gen l`i'vburcap=l`i'.vburcap
			}
			sum year cow
			xtset cow year
 
			gen vdem_democracy=v2x_regime>=2 & v2x_regime!=.
			tab vdem_democracy
			tsset cow year
			gen l1vdem_democracy = l.vdem_democracy
			gen enddem = vdem_democracy==0 & l1vdem_democracy==1
			btscs enddem year cow if l1vdem_democracy==1, g(demyrs) 
			
			 ** 
			 recode cow (679=678) if year==1990 & vdem_country=="Yemen"
			 recode cow (260=255) if year>1945 & year<=1990 & vdem_country=="Germany"
			 recode cow (316=315) if year==1993 & vdem_country=="Czech Republic"
 
			* Merge GWF data *
			sort cow year
			merge cow year using "GWFglobal2020.dta"
			sum year if v2x_polyarchy~=.
			sum year if gwf_country ~=""
			tab _merge if year>=1980  & year<=2019  /* All GWF data in the data set */
			drop if _merge==1
			rename _merge merge1
			
 
			keep if year>=1980 & year<=2020
 			xtset cow year
			sort cow year
			merge cow year using wdi-merge
			tab _merge
			rename _merge merge2
			tab gwf_country if merge2==1 /* note that South Sudan, Swaziland, and Taiwan (2000) are missing from WDI */
			tab wdi_country if merge2==2
			
			drop if merge2==2
			replace cow =626 if gwf_country=="South Sudan"
			xtset cow year
			gen l1gdp =l.gdp
			local var ="l1gdp lpop imr"
			foreach v of local var {
				qui xi: reg `v'   i.year*e_migdppcln i.cow*e_migdppcln 
				qui predict hat,xb
				replace `v'  =hat if `v' ==.
				drop hat
			}
		 			
			sort cow year
			merge cowcode year using prio-mergeB
			tab _merge
			rename _merge merge5
			drop if year<1980
			tab merge5
			sum year if merge5==2  /* all in 2018 */
			drop if merge5==2
			recode prio_conflict* prio_lconflict* (.=0) if year<=2018
			sort cowcode year
 			save master,replace
			
			insheet   using "reign-regime.csv",clear
			gen sdate = date(gwf_startdate, "MDY")
			gen edate = date(gwf_enddate, "MDY")
 			gen syear = year(sdate)
			gen eyear = year(edate)
			gen duration = eyear-syear +1
			expand duration
			gen n=_n
			egen m = min(n),by(gwf_casename)
			gen year =syear+1 if m==n
			sort gwf_casename year
			replace year = year[_n-1]+1 if year==.
			drop if year>eyear & year<=2019 & gwf_enddate~="12/31/2019"
			drop if year==2020 & gwf_enddate~="12/31/2019"
			keep if year>1987 & year<=2020
			recode cowcode (679=678) if year>=1991
			recode cowcode (316=315) if year==1993
			recode cowcode (260=255) if year<=1990
			local var = "country startdate enddate regimetype casename"
			foreach v of local var {
				rename gwf_`v' reign_`v'
			}
			sort cow year
			xtset cowcode year
			merge cow year using master
			tab _merge
			tab gwf_country if _merge==2  /* Taiwan not in reign data */
			drop if _merge==1
			rename _merge merge6
			drop sdate edate syear eyear duration n m
			sort cowcode year
			save master, replace
			
			insheet using "world-bank-statistical-capacity-indicators.csv",clear   names
			rename countryname country
			rename Time year
			gen n = _n
			tab year if n>9240
			drop if n>9240
			destring year,replace
			drop time  
			rename methodologyassessmentofstatis wb_stat_capacity
			rename overallaverageiqsciovrl wb_stat_ave
			rename sourcedataassessmentofstatis wb_stat_source
			rename periodicityandtimelinessasses wb_stat_periodicity
			gen cowcode=.
			qui do cowcodes
			drop if cowcode==.
			rename country wb_country
			local var = "wb_stat_capacity wb_stat_ave wb_stat_source wb_stat_periodicity"
			foreach v of local var {
				replace `v'="." if `v'==".."
				destring `v',replace
				replace `v'=`v'/100
				xtset cowcode year
				gen l1`v'=l.`v'
			}
			drop n
			sort cowcode year
			merge cowcode year using master
			tab _merge
			drop if _merge==1
			rename _merge merge7
			sort cowcode year
			tsset cowcode year
			save master, replace
			
			merge cowcode year using statecapacity_merge
			tab _merge
			tab vdem_country if _merge==1 & year>1988 & year<=2015
			rename _merge merge8
			drop if merge8==2
			rename Capacity hansonsigman_capacity
			rename Capacity_ hansonsigman_capacity_sd
			tsset cowcode year
			gen l1hansonsigman_capacity=l.hansonsigman_capacity
			gen l2hansonsigman_capacity=l2.hansonsigman_capacity
			sort cowcode year
			save master, replace
		 
		    use "qog2020.dta",clear  /* downloaded 8/18/20 from https://qog.pol.gu.se/data/datadownloads/qogbasicdata */
			gen cowcode = ccodecow
			keep cowcode year wdi_tacpsr  icrg_qog cname
 			rename cname qog_cname
			rename wdi_tacpsr qog_wdi_tacpsr  
			rename icrg_qog qog_icrg_qog 
			recode cow (679=678) if year>1990
			sort cowcode year
			merge cowcode year using master,
			tab _merge if year<2020
			tab country if _merge==2  & year<2020
			drop if _merge==1
			rename _merge =merge9
			tsset cowcode year
			sort cowcode year
			save master,replace
		
		
************************************************
************* Personalist Party data ***********
************************************************

	*****************************
	*** Import and clean data ***
	*****************************
	import excel using "Personalist-Parties-Final",clear firstrow  
	drop  *_s electing_p_prior_elect_national_
	sum year
	keep if year>=1990
 	
	* List and drop technocratic appointments *
		egen tag=tag(current_leader) if electing_p_name=="Technocrat appointment"
		list country current_leader if tag==1
		drop if electing_p_name=="Technocrat appointment"
		drop tag

		tab current_p_create,m
		tab electing_p_create,m
		tab current_p_name if current_p_create==9  /* These are the true independents who never form a party while in office */
		tab current_p_create if current_p_name=="Technocrat appointment"  /* These are technocrats who don't have parties */
		tab electing_p_name if electing_p_create==9 
		tab electing_p_create if electing_p_name=="Technocrat appointment"  /* These are technocrats who don't have parties */
		tab electing_p_create if electing_p_name=="N/A"
		list current_p_name country year current_leader if electing_p_name=="N/A", noobs clean
		
		tab electing_p_name if electing_p_merge==9
		tab electing_p_merge_month if electing_p_merge==9
		tab electing_p_merge_year if electing_p_merge==9
		tab electing_p_founding_month if electing_p_merge==9
		tab electing_p_founding_year if electing_p_merge==9
 	    	
	******************
	*** Clean data ***
	******************
		recode current_p_create electing_p_create (9=3)  /* no party==sole party creation */
		recode current_p_create current_p_leader_family current_p_creator_family ///
		current_p_prior_elect_local current_p_prior_appt_local current_p_prior_elect_nati ///
		current_p_prior_appt_na current_p_prior_national_p electing_p_create ///
		electing_p_leader_family electing_p_creator_family electing_p_prior_elect_loc ///
		electing_p_prior_appt_l electing_p_prior_elect_nat electing_p_prior_appt_n ///
		electing_p_prior_national_p prior_p_1_create prior_p_1_leader_family ///
		prior_p_1_creator_family prior_p_1_prior_elect_loca prior_p_1_prior_appt_lo ///
		prior_p_1_prior_elect_nati prior_p_1_prior_appt_na prior_p_1_prior_national_p ///
		prior_p_2_leader_family prior_p_2_create prior_p_2_creator_family prior_p_2_prior_elect_loca ///
		prior_p_2_prior_appt_lo prior_p_2_prior_elect_nati prior_p_2_prior_appt_na ///
		prior_p_2_prior_national_p (9=.)
	 
	******************************
	*** Variable construction  ***
	******************************	 
		* Recode missing to zero *
		recode prior_p_1_prior_elect_loca prior_p_1_create prior_p_1_leader_family ///
			prior_p_1_creator_family  ///
			prior_p_1_prior_appt_lo prior_p_1_prior_elect_nati ///
			prior_p_1_prior_appt_na prior_p_1_prior_national_p (.=0)
		recode electing_p_prior_elect_loc electing_p_prior_appt_l ///
			electing_p_prior_elect_nat electing_p_prior_appt_n ///
			electing_p_prior_national_p (.=0)
		recode electing_p_leader_family electing_p_creator_family (.=0)
		
		* Short names *
		gen localelect = electing_p_prior_elect_l
		gen localappt = electing_p_prior_appt_l 
		gen natelect = electing_p_prior_elect_n
		gen natappt = electing_p_prior_appt_n
		gen natparty = electing_p_prior_national_p
			    
		* Binary party creation variable, not merger *
		gen create = electing_p_create==1 | electing_p_create==3 | electing_p_name=="N/A"  
  
		* Prior independent grouped together *
		recode indep* (9=0)
		sum indep*
		gen priorindep = indep_prior_local_elect==1 |  indep_prior_local_appt==1 | ///
			indep_prior_national_elect==1 | indep_prior_national_appt==1 | ///
			indep_prior_national_defea==1		
		
		* Leaders *
		egen lid = group(leaderid)
		egen minyr = min(year),by(lid)

		* Party age *
		gen partyage = current_leader_start_year-electing_p_founding_year if electing_p_founding_year>0
		browse country year current_leader current_p_name current_p_create if electing_p_founding_year==0
		recode partyage (.=0) 
		replace partyage=0 if partyage<0
		gen lnpartyage =ln(1+partyage)
 
		* Experience in the party *
		replace first_year_exp="." if first_year_exp=="N/A"
		replace year_date_position="." if year_date_position=="N/A"
		destring year_date_position first_year_exp,replace
		sum year year_date_position first_year_exp
		gen timeparty = current_leader_start_year-first_year_exp
		replace timeparty =0 if timeparty==. | timeparty<0
		centile partyage if create==0,centile(50) /* old parties */
		centile timeparty if create==0,centile(33.33)  /* not super new party experience */
		gen partyexp = partyage>44 & timeparty>=10
		tab partyexp create
		
		* Flip scale so 1 \equiv more personalist *
		recode localappt natelect natappt natparty localelect partyexp (1=0) (0=1)
 
		* Set sample *
		gen cowcode = ccode
		drop if cowcode==.
		sort cowcode year
		xtset cowcode year

		* Variables for 8-item IRT *
		factortest natelect natappt natparty localappt create localelect priorindep partyexp
		factor     natelect natappt natparty localappt create localelect priorindep partyexp,mineigen(.25)  
 		screeplot,tit(Eigen values for 8 items)saving(h1.gph,replace)xlab(0(2)8)
		loadingplot,saving(h2.gph,replace)
		gr combine h1.gph h2.gph,xsize(8)
		gr export "C:\Users\jgw12\Dropbox\Research\PersParty\Manuscript\golden\factor.pdf",as(pdf)replace 
  		erase h1.gph
		erase h2.gph

		* IRT *
		sum create natelect natappt natparty localelect localappt priorind partyexp
		polychoric create natelect natappt natparty localelect localappt priorind partyexp
		tab localappt create
		tab partyexp create
		tab localappt priorind
		corr create natelect natappt natparty localelect localappt priorind partyexp
		alpha  create natelect natappt natparty localelect localappt priorind partyexp,item detail std

		 /* local elect contributes the least info */
 		irt (2pl create natelect natappt natparty localelect localappt priorind partyexp),vce(cluster lid) 
		irtgraph iif (create,lcol(red)) (partyexp,lcol(cyan)lpat(solid))  ///
			(natelect,lcol(blue*.5)lpat(solid)) (natappt,lcol(blue*1.5)lpat(dash)) ///
			(priorind,lcol(magenta)lpat(solid)) (natparty,lcol(orange)lpat(solid))  ///
			(localappt,lcol(green*0.5)lpat(solid)) (localelect,lcol(green*1.5)lpat(dash)) 
		gr export "C:\Users\jgw12\Dropbox\Research\PersParty\Manuscript\golden\iif.pdf",as(pdf)replace 
		estat ic
		irtgraph icc (create,lcol(red*1.5)lpat(solid))(natelect,lcol(blue*1.5)lpat(dash))(localelect,lcol(red)lpat(dash)) ///
			(partyexp,col(yellow*1.5)lpat(solid)) ///
			(priorind,lcol(green))(natappt,lcol(blue*0.8)lpat(solid))(natparty,lcol(brown)lpat(solid))(localappt,lcol(cyan)lpat(solid)) 
		gr export "C:\Users\jgw12\Dropbox\Research\PersParty\Manuscript\golden\icc.pdf",as(pdf)replace 
		predict persparty,latent ebmeans se(se_pers)
		
		*** Plot IRT model parameter estimates ***
		gen a1 = "&"
		gen a2 = "&"
		gen a3 = "&"
		gen a4 = "&"
		gen a5 = "&"
		gen a6 = "&"
		gen b = "\\"
		gen discr=.
		gen diff=.
		gen hi_disc = .
		gen lo_disc = .
		gen hi_diff = .
		gen lo_diff = .
		gen xn = _n
		gen var = ""
		irt (2pl create natelect natappt natparty localelect localappt priorind partyexp),vce(cluster lid) 
		mat e = e(b)
		mat var = r(V)
		forval i = 1(2)15 {
			qui replace discr=e[1,`i'] if xn==`i'
			qui local v = sqrt(var[`i',`i']) 
			qui replace hi_disc =  e[1,`i'] + 1.96*`v' if xn==`i'
			qui replace lo_disc =  e[1,`i'] - 1.96*`v' if xn==`i'
		}
		forval i = 2(2)16 {
			local j = `i'-1
			qui replace diff= -1*(e[1,`i']/e[1,`j']) if xn==`i'-1
			local v =  sqrt(var[`i',`i'])
			qui replace hi_diff = (-1*(e[1,`i']/e[1,`j'])) + 1.96*`v' if xn==`i'-1
			qui replace lo_diff = (-1*(e[1,`i']/e[1,`j'])) - 1.96*`v' if xn==`i'-1
		}
		qui replace var = "create" if xn==1
		qui replace var = "natelect" if xn==3
		qui replace var = "natappt" if xn==5
		qui replace var = "natparty" if xn==7
		qui replace var = "localelect" if xn==9
		qui replace var = "localappt" if xn==11
		qui replace var = "priorind" if xn==13
		qui replace var = "partyexp" if xn==15
		list var a1 hi_disc  discr   lo_disc a4  hi_diff   diff   lo_diff  if xn<=16,clean noobs
		twoway (rspike hi_disc lo_disc xn  if xn<=16,horizontal xline(0) tit(Discrimination)) ///
			(scatter xn disc if xn<=16,msym(P)saving(h1.gph,replace)legend(off)ytit(Item)xtit(Information) ///
			ylab(1 "create party" 3 "national elected" 5 "national appointed" 7 "party leadership" ///
			9 "local elected" 11 "local appointed" 13 "prior indep." 15 " party exper."))
		twoway (rspike hi_diff lo_diff xn if xn<=16,xline(0)tit(Difficulty)horizontal) ///
			(scatter xn diff if xn<=16,msym(P)saving(h2.gph,replace)legend(off)ytit(Item)xtit({&theta}) ///
			ylab(1 "create party" 3 "national elected" 5 "national appointed" 7 "party leadership" ///
			9 "local elected" 11 "local appointed" 13 "prior indep." 15 " party exper."))
		gr combine h1.gph h2.gph
		erase h1.gph
		erase h2.gph
		gr export "C:\Users\jgw12\Dropbox\Research\PersParty\Manuscript\golden\irt-information.pdf",as(pdf)replace 

		* Inverse logit the discrimination parameters *
		qui replace disc =invlogit(disc) -.5
		list var a1 discr b if xn<=16,clean noobs
		alpha create natelect natappt natparty localelect localappt priorind partyex,item
		drop discr diff xn var a1 a2 a3 a4 a5 a6 hi_* lo_* b

		hist persparty   
		sum persparty		
		replace persparty =(persparty+abs(r(min)))/(abs(r(min)) + r(max))
		sum persparty		
	 	  
		*** Additional measurement models ***
			* Linear link functions *
		gsem (PER->create natappt localappt natelect natparty localelect priorind partyexp,var(PER@1)),vce(cluster lid)
		predict gauss_nocov,latent ebmeans
		gsem (PER->create natappt localappt natelect natparty localelect priorind partyexp,var(PER@1)), ///
			cov(e.natappt*e.localelect e.create*e.natparty e.natparty*e.localappt e.create*e.partyexp)vce(cluster lid)
		predict gauss_cov,latent ebmeans
			* Mixed link functions *
		gsem (PER->localappt localelect create natelect natappt natparty priorindep,logit var(PER@1)) ///
			(PER-> partyexp,reg var(PER@1)),vce(cluster lid)
		predict persparty_mix,latent ebmeans
		estat ic
		corr persparty* gauss*
		xtset cow year
		xtsum persparty*  gauss*
		drop gauss* persparty_mix
		 
		save "C:\Users\jgw12\Dropbox\Research\PersPartyBook\Data\pers-temp.dta",replace	
		save pers-temp,replace
	
		
		***************************************************************
		**** Expand VDem party data into country-party-year format ****
		***************************************************************
		 use V-Dem-CPD-Party-V1,clear
		 drop if v2paid==.
		 egen maxc  =max(year),by(country_name)
		 gen maxyrc = maxc==year
		 sort v2paid year
		 bysort v2paid: gen diff =  year[_n+1]-year
		 
		 * Carry forward to 2020 *
		 replace diff = 2020-year+1 if maxyrc==1
		 sort v2paid year
		 bysort v2paid:replace diff = diff[_n-1]+1 if diff==. & v2paid==v2paid[_n-1]
 		 replace diff=2 if year==2019
		 
		 * Carry forward from last election for the Party ID *
		 egen max  =max(year),by(v2paid)
		 gen maxyr =max==year
		 replace diff = 12 if maxyr==1
		 drop max maxyr
	  
		 expand diff
		 gen yr = year
		 sort country_name v2paid year
		 bysort country_name v2paid:replace yr = yr[_n-1]+1 if year==year[_n-1] & v2paid==v2paid[_n-1]  
		 replace diff=1
		 
		* Carry backwards one year from first election for the Party ID *
		 sort v2paid year
		 egen min  =min(yr),by(v2paid)
		 gen minyr =min==yr
		 replace diff = 6 if minyr==1
		 expand diff
		 drop min minyr
		 sort country_name v2paid yr
		 bysort country_name v2paid:replace yr = yr-1 if yr==yr[_n+1] & v2paid==v2paid[_n+1] & diff>=2 
 		 sort country_name v2paid yr
		 bysort country_name v2paid:replace yr = yr-1 if yr==yr[_n+1] & v2paid==v2paid[_n+1] & diff>=2 
		 sort country_name v2paid yr
		 bysort country_name v2paid:replace yr = yr-1 if yr==yr[_n+1] & v2paid==v2paid[_n+1] & diff>=2 
 		 sort country_name v2paid yr
		 bysort country_name v2paid:replace yr = yr-1 if yr==yr[_n+1] & v2paid==v2paid[_n+1] & diff>=2 
		 sort country_name v2paid yr
		 bysort country_name v2paid:replace yr = yr-1 if yr==yr[_n+1] & v2paid==v2paid[_n+1] & diff>=2 
		 
		 drop year diff
		 rename yr year
		 sort v2paid year
		 save vdem-parties-merge,replace
		
		 *****************************************************************************
		 *** Merge VDem country-party-year data with personalist country-year data ***
		 *****************************************************************************
		use pers-temp,clear
		keep if year>=1991  
		gen v2paid = electing_p_id
 		list country year current_leader electing_p_name  ///
			if current_p_id=="N/A" | current_p_id=="" & ///
			(current_p_name=="N/A" |current_p_name=="" | ///
			current_p_name=="Technocrat appointment"), noobs clean
		list country year current_leader electing_p_name if  electing_p_id==.,noobs clean 
			
		/* We have double-checked these parties, which do not appear in the VDem parties data set:
		(1) Nepali Congress (Democratic)-NC (D) is not the same (in 2005) as the Nepali Congress (ID 3756)
		(2) Unified Communist Party of Nepal (Maoist)-UCPN (M) is not the same as 
			Communist Party of Nepal (Unified Marxist-Leninist)-CPN (UML) (ID 3755)
		(3) Sri Lanka Podujana Peramuna (SLPP) postdates the VDem parties data set: 
			The SLPP was effectively re-launched in November 2016 by Mahinda Rajapaksa; 
			The Sri Lanka National Front (SLNF) was minor party renamed Our Sri Lanka Freedom Front (OSLFF) 
			in 2015; However, OSLFF was relaunched by Mahinda Rajapaksa in 2016 as the Sri Lanka Podujana 
			Peramuna (SLPP) and became the home for Rajapaksa supporters and Rajapaksa-faction members 
			of the United People’s Freedom Alliance (UFPA) and Sri Lanka Freedom Party (SLFP), both
			of which had backed Mahinda Rajapaksa in the 2005 election.
		(4) Shekhar broke with the Janata Dal Party on November 5, 1990 and formed the 
			Janata Dal-Socialist faction. When selected PM in in Nov 1990, Shekhar was backed by the INC
			but his party was the Janata Dal-Socialists not the rump Janata Dal Party (ID 1207)
		(5) AKFM-Fanavaozana split from AKFM in 1989 when AKFM refused to nominate Andriamanjato as its
			presidential candidate. In 1990, AKFM-Fanavaozana joined with other opposition groups 
			to form the Comité des Forces Vives (ID 5368) and backed Zafy in the 1993 presidential election.
		(6) New Force for Madagascar (Hery Vaovao ho an’i Madagasikara–HVM) is not included in VDem-Parties; 
			PartyFacts group HVM and TGV together as other (ID 5207)
		(7) Madagascar	2019 Rajoelina	TGV not in VDem-Parties but has a grouped PartyFacts ID (5207)
		(8) Sovereign Communists/Party of Power in Urkaine was the grouping of supporters for Kravchuk; 
			These groups were not formally registered political parties. VDem
			does not record this grouping as political party during this period.
		(9) National Reconstruction Party (PRN) in Brazil 1991-1992 has a PartyFacts ID (4410) but
			is not included in the VDem-Parties data.
		(10) Peasant Response Party - Haiti/Martelly 2011 - has a PartyFactsID (6069) but not in VDem-Parties.
		(11) Ukraine's Inter-Regional Bloc of Reforms (MRBR) (PartyFacts ID 2227) is not in VDem-Parties.
		(12) Ukraine's Sovereign Communists/Party of Power has neither a PartyFacts ID nor is in VDem-Parties.
		(13) (North) Macedonia's Social Democratic Union of Macedonia (PartyFacts ID 1508) 
			 is not in VDem-Parties.
		(14) Slovenian Christian Democrats (Slovenski krščanski demokrati, SKD, PartyFactsID 644) is
			 not in VDem-Parties.
		(15) Lithuania's Sajudis Party/Sajudzio koalicija (1991) has PartyFacts ID 743 but
			 is not in VDem-Parties.

		*/
		sort v2paid year
		merge v2paid year using vdem-parties-merge, 
		tab _merge
		drop if _merge ==2
		egen tag = tag(country current_leader) if _merge==1
		list country year current_leader electing_p_id electing_p_name if tag==1, noobs clean
		drop _merge
 		xtset cowcode year
	
		sort cowcode year
		merge cowcode year using master
		tab _merge
		list country year if _merge==1,clean noobs
		drop if _merge==1
		drop _merge
		xtset cowcode year
		gen lv2paind= l.v2paind 
		recode gwf_back (.=0) if country=="Luxembourg"

		gen type = reign_regimetype
		sort cowcode year
		replace type = reign_regimetype[_n-1] if type~="presidential" & type~="parliamentary"
		sort cowcode year
		replace type = type[_n-1] if type~="presidential" & type~="parliamentary"
		
		gen demsample= year>=1991 & year<=2020 & gwf_back~=. & (gwf_regime=="democracy" | gwf_regime=="provisional")
		keep if (gwf_regime=="democracy" | gwf_regime=="provisional") & year>=1991
		keep if current_leader~=""
				
		local var = "persparty"
		foreach v of local var {
			qui sum `v'  if persparty~=.
			replace `v' =(`v'+abs(r(min)))/(abs(r(min)) + r(max))
		}
		
		xtsum  	  persparty*
		sfrancia  persparty* 
	
	   gen ovdem  = l1v2x_polyarchy if year==min
	   bysort lid: egen ivdem=max(ovdem)
						
			*** Time period and geographic region ***
			gen period =  year<=1995
			replace period = 2 if year>1995 & year<=2000
			replace period = 3 if year>2000 & year<=2005
			replace period = 4 if year>2005 & year<=2010
			replace period = 5 if year>2010 & year<=2015
			replace period = 6 if year>2015  
			gen xperiod1 = year<=1995
			gen xperiod2 = year>1995 & year<=2000
			gen xperiod3 = year>2000 & year<=2005
			gen xperiod4 = year>2005 & year<=2010
			gen xperiod5 = year>2010 & year<=2015
			gen xperiod6 = year>2015  
			tab period
			recode e_regionpol_6C (2=4) if country=="Guinea Bissau"
			egen pregion = max( e_regionpol_6C),by(cowcode)
			tab pregion, m
			recode pregion  (.=5) /* Afghanistan */
			
 
		xtset lid year
		gen l1v2paind = l.v2paind
		replace v2paind=l1v2paind if l1v2paind!=. &  v2paind==.
		recode gwf_back (.=0) if country=="Luxembourg"
 		sort cowcode year
		replace type = reign_regimetype[_n-1] if type~="presidential" & type~="parliamentary"
		sort cowcode year
		replace type = type[_n-1] if type~="presidential" & type~="parliamentary"

		gen ld = ln(1+gwf_duration) 
		gen civwar = prio_lconflict_int_intra==2
		gen civwarany = prio_lconflict_int_intra==2 |  prio_lconflict_int_intra==1
		gen intwar =prio_lconflict_cumint_inter 
		gen seat50 = v2paseatshare>=50 if v2paseatshare~=.
		gen priormil = gwf_priorregim=="military" | gwf_priorregim=="indirect military"
* Flag *				 
		keep if year>1990 & year<=2020 & gwf_back~=. & (gwf_regime=="democracy" | gwf_regime=="provisional")
 		tsset cowcode year
		sort cowcode year
		saveold pers-use,version(12) replace

		 
	*************************************
	*****  State capacity Analysis ******
	*************************************
		use pers-use,clear 
 		global x ="ld ivdem v2paseatshare"
 		global ldv ="l1vburcap l2vburcap"
		global d="v2paind"
		global t = "time time2"
		qui  reghdfe vburcap $d $ldv $x,a(cowcode year)cluster(cowcode)
		gen sample=e(sample)
		tab sample
		
		gen time = year-1990
		gen time2 = time^2
		
		************************
		*** Descriptive data ***
		************************	
		* Standardize key variables *
		local var ="v2paind vburcap l1vburcap l2vburcap vburcap4 vaccess vmilitary vfiscal vterrit vlegibility v2clrspct v2strenadm v2stcritrecadm v2x_pubcorr v2cltrnslw persparty"
		foreach v of local var {
			qui sum `v' if sample==1
			local m=r(mean)
			if `m'<0 {
				replace `v'=(`v'+abs(r(mean)))/r(sd)
			}
			else if `m'>0 {
				replace `v'=(`v'-abs(r(mean)))/r(sd)
			}
		}
		
		hist vburcap if sample==1,bin(100)saving(h1.gph,replace)xtit(Bureaucratic capacity)normal
		hist v2paind if sample==1,bin(100)saving(h2.gph,replace)xtit(Party personalism)normal
		gr combine h1.gph h2.gph,xsize(8)ysize(4)tit(Distribution of key variables)
		gr export "$dir\golden\distributions.pdf",as(pdf)replace 
		
		label var year "Year"
		label var v2paind "Party personalism"
		label var vburcap "Bureaucratic capacity"
		label var ld "Democracy age (log)"
		label var lnparty "Party age (log)"
		label var create "Party creation"
		label var persparty "Pre-electoral party personalism"
		label var v2clrspct "Impartial administration"
		label var v2strenadm "Administrative renumeration"
		label var v2stcritrecadm "Administrative appointments"
		label var v2x_pubcorr "Public sector corruption"
		label var v2cltrnslw "Predictable enforcement"
		sutex2 year l1v2paind vburcap ld lnparty create persparty v2clrspct v2strenadm v2stcritrecadm ///
			v2x_pubcorr v2cltrnslw if sample==1,minmax digits(2) varlabels  
 		 * Within variation for main outcome variables *
		 local var = "vburcap vfiscal vterritory hansonsigman_capacity"
		 foreach i of local var {
			qui xtset cowcode year
			qui xtsum `i' if sample==1
			scalar sdb`i' = r(sd_b)
			scalar sdw`i' = r(sd_w)
			scalar vart`i'= sdb`i' + sdw`i'
			scalar varr`i' = sdw`i' / vart`i'
			scalar list varr`i'
		 }
		 gen n =.
		 gen totalvar = .
		 gen ratio  = .
		 gen tp = ""
		 local c = 1
		 local vars = "vburcap vfiscal vterritory hansonsigman_capacity"
		 foreach i of local vars {
			replace n = `c'
			replace totalvar = vart`i' if n==_n
			replace ratio = varr`i' if n==_n
			replace tp = "`i'" if  n==_n
			local c = `c' + 1
		 }
		 gen t = ""
		 replace t =  "Bureaucratic cap." if tp=="vburcap"		 
		 replace t =  "Fiscal" if tp=="vfiscal"
		 replace t =  "Territory" if tp=="vterritory"
		 replace t =  "Hanson-Sigman" if tp=="hansonsigman_capacity"
		 twoway (scatter ratio total, mlabel(t) mlabpos(12) xtitle("Total variance") ytitle("Within/Total") ///
			  ylab(0(.2).4,glcol(gs15)) xlab(1 (.2) 1.4) yscale(range(.4)) xscale(range(1 1.4))  ///
			  title("Within variation"))   
		 gr export "$dir\golden\within-variation.pdf",as(pdf)replace 
		 drop t tp totalvar ratio n
		 
		 * External validity check of vburcap *		 
		 spearman vburcap qog_icr
		 qui reg vburcap i.cowcode i.year if qog_icrg~=.
		 predict hat_cap if e(sample)==1
		 qui reg qog_icrg i.cowcode i.year if vburcap~=.
		 predict hat_icrg if e(sample)==1	
		 reghdfe qog_ic vburcap time time2 if sample==1,a(cowcode) cluster(lid)
		 twoway (scatter hat_icrg hat_cap) (lpolyci hat_icrg hat_cap,xtit("Impartial administrative capacity" "(residualized)") ///
			ytit("ICRG Quality of Government" "(residualized)") legend(off) tit(ICRG Indicator of Quality of Government) ///
			note("Partial correlation after adjusting for country effects and time trend",pos(6)size(vsmall)) ///
			text(.92 -.5 "{&beta}=0.031*") text(.88 -.5 "(se=0.011)",size(vsmall))saving(h1.gph,replace))
		 drop hat*
		 spearman vburcap wb_stat_ave
		 qui reg vburcap i.cowcode i.year if wb_stat_ave~=.
		 predict hat_cap if e(sample)==1
		 qui reg wb_stat_ave i.cowcode i.year if vburcap~=.
		 predict hat_wb if e(sample)==1	
		 reghdfe wb_stat_ave vburcap time time2 if sample==1,a(cowcode) cluster(lid)
		 twoway (scatter hat_wb hat_cap) (lpolyci hat_wb hat_cap,xtit("Impartial administrative capacity" "(residualized)") ///
			ytit("WB statistical capacity" "(residualized)") legend(off) tit(World Bank Statistical Capacity Indicator) ///
			note("Partial correlation after adjusting for country effects and time trend",pos(6)size(vsmall)) ///
			text(.92 -1.5 "{&beta}=0.032*") text(.88 -1.5 "(se=0.016)",size(vsmall))saving(h2.gph,replace))
		 drop hat*
		 gr combine h1.gph h2.gph,xsize(8)
		 gr export "$dir\golden\vburcap-external-validity.pdf",as(pdf)replace 
		 
		 reghdfe qog_icrg l.qog_icrg l2.qog_icrg $d $x,absorb(cowcode year)
		 reghdfe wb_stat_ave l.wb_stat_ave l2.wb_stat_ave $d $x,absorb(cowcode year)
		 
		 ** Flag first year of each leader-spell to calcuate initial level of DV for each leader-spell **
		 egen maxcreate = max(create),by(cowcode)
		 egen mincreate = min(create),by(cowcode)
		 
		 centile v2paind if sample==1,centile(50)
		 gen treat1 = v2paind>=r(c_1) if v2paind~=.
		 tab treat1 if sample==1
		 egen c =count(year) if sample==1,by(gwf_caseid)  /* for WFE keep only democracies that last 3 or more years */
		 tab gwf_casename if c<2 & sample==1   /* singleton panels dropped in FE analysis */
		 
		 * Initial level *
		 gen vburcap0=l1vburcap if year==minyr
		 egen ivburcap=max(vburcap0),by(lid)
		 
		 * Right-left pop *
		 qui centile v2xpa_popul if sample==1,centile(75)
		 local p1=r(c_1)
		 qui centile v2pariglef if sample==1,centile(25 75)
		 local c1 =r(c_1)
		 local c2 =r(c_2)
		 gen rightpop = v2xpa_popul>`p1' & v2pariglef>`c2'
		 gen leftpop = v2xpa_popul>`p1'  & v2pariglef<1`c1'
		 
		 sort cowcode year
		 saveold pers-useid,version(12) replace
		 
		 *********************************
		 *** Partial correlation plots ***
		 *********************************
		 use pers-useid,clear
		 qui centile v2paind if vburcap~=. & ld~=. & sample==1,centile(50)
		 local c= r(c_1)
		 gen hipers = $d>`c'
		 gen e=.
		 gen hi=.
		 gen lo=.
		 gen n=_n
		 tab hipers  if vburcap~=. & ld~=.
		 ttest vburcap if vburcap~=. & ld~=.,by(hipers)
		 local  m1=r(mu_1) 
		 local se1 = r(sd_1)/(sqrt(r(N_1)))
		 local  m2=r(mu_2)
		 local se2 = r(sd_2)/(sqrt(r(N_2)))
		 replace e=`m1' if _n==1
		 replace hi = `m1' + 1.96* `se1' if _n==1
		 replace lo = `m1' - 1.96* `se1'  if _n==1
		 replace e=`m2' if _n==2
		 replace hi = `m2' + 1.96*`se2' if _n==2
		 replace lo = `m2' - 1.96*`se2' if _n==2				
		 twoway (bar e n if n<=2,barwidth(.4)yline(0,lpat(solid))bcol(gs13)ytit(Impartial state administration)saving(h1.gph,replace)) ///
				(rspike hi lo n if n<=2,ylab(-.5(.5).5)col(gs1)legend(off)xtit("Party personalism level")  ///
				xlab(1 "Low party personalism" 2 "High party personalism")xscale(range(.7 2.3)) ///
				text(.25 1 "0.384",size(small)) text(-.3 1.98 "-0.438",size(small))tit(Difference of means test))
		 
		 reg v2paind ld ivdem if sample==1
		 predict partialpersparty if sample==1, res
		 corr partial v2paind
		 reg vburcap v2paind if partial~=.,cluster(lid)
		 reg vburcap partial if partial~=.,cluster(lid)
		 twoway (lpolyci vburcap v2paind,bw(1))  (lpolyci vburcap partial,bw(.75) ///
			ytit(Impartial state administration,height(0))xtit(Party personalism) ///
			legend(lab(2 "Unadjusted party personalism (-0.422*)") lab(3 "Adjusted party personalism (-0.200*)") ///
			order(2 3)pos(7)ring(0)size(vsmall)col(1))tit(Raw and adjusted data patterns)saving(h2.gph,replace) ///
			note("Adjusted party personalism partials out initial level of democracy and democracy age", ///
			size(vsmall)pos(6)))
		gr combine h1.gph h2.gph
		gr export "$dir\golden\ttests.pdf",as(pdf)replace 
		erase h1.gph 
		erase h2.gph
		
		*** Time trend in vburcap is roughly linear ***
		use pers-useid,clear
		twoway (lpolyci vburcap year,bw(4)yaxis(2)) ///
			(lpolyci v2paind year,bw(4)xtit(Year)ytit(Variable scale) ///
			legend(lab(2 "Impartial state admin")lab(3 "Party personalism") ///
			order (2 3)pos(6)ring(1)col(2)size(small))ysize(6))
		gr export "$dir\golden\linear-time-trend.pdf",as(pdf)replace 
		qui reghdfe vburcap  ivburcap $d $x time if sample==1,absorb(cowcode)vce(cluster lid)
		test time
		qui reghdfe vburcap  ivburcap $d $x time time2 if sample==1,absorb(cowcode)vce(cluster lid)
		test time time2
		gen time3=time^3
		qui reghdfe vburcap  ivburcap $d $x time time2 time3 if sample==1,absorb(cowcode)vce(cluster lid)
		test time time2 time3
				
				
		***********************
		*** Estimate models ***
		***********************
		use pers-useid,clear
		global x ="ld ivdem v2paseats"
 		global ldv ="l1vburcap l2vburcap"
		global d="v2paind"
		global t = "time time2"
		drop ivburcap vburcap0
		 ** (1) 2-way FE w/ & (2) w/out cov adj; (3) 2-way FE w/ initial level of DV; (4) FE w/ lag DVs  
		 local var = "v2clrspct v2strenadm v2stcritrecadm v2x_pubcorr v2cltrnslw vburcap hansonsigman_capacity v2x_execorr v2xnp_regcorr v2peasbepol v2peasjpol vfiscal vterritory "
		 foreach v of local var { 
			qui sum `v' if persparty~=.
			qui replace `v' =(`v'-r(mean))/r(sd)
			ttest `v' if maxcreate==1 & mincreate==0,by(create)
			gen `v'0=l1`v' if year==minyr
			egen i`v'=max(`v'0),by(lid)
			qui reghdfe `v' $d time if sample==1, absorb(cowcode)vce(cluster lid)
			lincom $d
			est store `v'1
			qui reghdfe `v' $d $x time if sample==1,absorb(cowcode)vce(cluster lid)
			lincom $d	
			est store `v'2
			qui reghdfe `v' i`v' $d $x time if sample==1,absorb(cowcode)vce(cluster lid)
			lincom $d
			est store `v'3
			qui reghdfe `v' l1`v' l2`v' $d $x time if sample==1,absorb(cowcode)vce(cluster lid)
			lincom $d
			est store `v'4
			drop i`v' `v'0
		 }
		
		 
		 label var $d " "
		 coefplot (vburcap1,msym(S)col(blue))(vburcap2,msym(O)col(blue))(vburcap3,msym(T)col(blue)) ///
				(vburcap4,msym(D)col(blue)),keep($d)ciopts(lcol(blue)) ///
				level(95) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.10(.02)0)legend(lab(2 "FE") ///
				lab(4 "FE" "+ cov. adj.") lab(6 "2FE" "+ initial capacity" "+ cov. adj.") ///
				lab(8 "FE + LDV"  "+ cov. adj."))note(95 pct CI,pos(6)size(vsmall)) ///
				title(Impartial state administration)
		 gr export "$dir\golden\bureaucratic-capacity.pdf",as(pdf)replace 

		coefplot (v2clrspct2,msym(S)col(blue))(v2stcritrecadm2,msym(O)col(blue))(v2strenadm2,msym(T)col(blue)) ///
				(v2x_pubcorr2,msym(D)col(blue)) (v2cltrnslw2,msym(Oh)col(blue)),keep($d)ciopts(lcol(blue blue)) ///
				level(95 90) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.12(.02)0)legend(lab(3 "Impartial" "administration") ///
				lab(6  "Administrative" "appointments" ) lab(9 "Administrative" "renumeration") ///
				lab(12 "Public sector" "corruption")lab(15 "Predictable" "enforcement"))  ///
				note("90 (thick) & 95 (thin) pct CI",pos(6)size(vsmall)) ///				 
				tit(FE,size(small))saving(h1.gph,replace)
		coefplot (v2clrspct4,msym(S)col(blue))(v2stcritrecadm4,msym(O)col(blue))(v2strenadm4,msym(T)col(blue)) ///
				(v2x_pubcorr4,msym(D)col(blue)) (v2cltrnslw4,msym(Oh)col(blue)),keep($d)ciopts(lcol(blue blue)) ///
				level(95 90) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.03(.01)0)legend(lab(3 "Impartial" "administration") ///
				lab(6  "Administrative" "appointments") lab(9 "Administrative" "renumeration") ///
				lab(12 "Public sector" "corruption")lab(15 "Predictable" "enforcement")) ///
				note("90 (thick) & 95 (thin) pct CI",pos(6)size(vsmall)) ///
				tit(FE + LDV,size(small))saving(h2.gph,replace)
		gr combine h1.gph h2.gph,xsize(8)ysize(4)iscale(.8)tit(Components of bureaucratic capacity)
		gr export "$dir\golden\components.pdf",as(pdf)replace 
		erase h1.gph
		erase h2.gph
		
		coefplot(v2x_execorr2,msym(O)col(blue))(v2xnp_regcorr2,msym(T)col(blue)) ///
				 (v2peasbepol2,msym(D)col(blue)) (v2peasjpol2,msym(S)col(blue)) ///
				 ,keep($d)ciopts(lcol(blue)) level(95) grid(glcolor(gs16))xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-.1(.05)0.15)legend(lab(2  "Executive" "corruption") ///
				lab(4 "Regime" "corruption") lab(6  "Access to" "state business") lab(8 "Access to" "state jobs")ring(0)) ///
				note(95 pct CI,pos(6)size(vsmall)) ///
				tit(FE,size(small))saving(h1.gph,replace)	
 		coefplot(v2x_execorr4,msym(O)col(blue))(v2xnp_regcorr4,msym(T)col(blue)) ///
				(v2peasbepol4,msym(D)col(blue)) (v2peasjpol4,msym(S)col(blue)) ///
				,keep($d)ciopts(lcol(blue))level(95)grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.04(.02)0.04)legend(lab(2  "Executive" "corruption") ///
				lab(4 "Regime" "corruption") lab(6  "Access to" "state business") lab(8 "Access to" "state jobs")ring(0)) ///
				note(95 pct CI,pos(6)size(vsmall))tit(FE + LDV,size(small))	saving(h2.gph,replace)
		gr combine h1.gph h2.gph,xsize(8)ysize(4)iscale(.8)tit(Additional state-related outcomes)
		gr export "$dir\golden\corruption.pdf",as(pdf)replace 
		erase h1.gph
		erase h2.gph
		coefplot  (vfiscal2,msym(T)col(blue)) ///
				(vterritory2,msym(D)col(blue))(hansonsigman_capacity2,msym(O)col(blue)), ///
				keep($d)ciopts(lcol(blue)) ///
				level(95) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.05(.05)0.05)legend(off) ///
				note(95 pct CI,pos(6)size(vsmall)) ///
				 tit(FE,size(small))saving(h1.gph,replace)
		coefplot  (vfiscal4,msym(T)col(blue)) ///
				(vterritory4,msym(D)col(blue)) (hansonsigman_capacity4,msym(O)col(blue)), ///
				keep($d)ciopts(lcol(blue)) ///
				level(95) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.05(.05)0.05)legend(lab(2 "Fiscal") ///
				lab(4 "Territory") lab(6 "") lab(6 "Hanson-" "Sigman" "composite" "capacity")ring(0)pos(7)) ///
				note(95 pct CI,pos(6)size(vsmall)) ///
				tit(FE + LDV,size(small))saving(h2.gph,replace)
		gr combine h1.gph h2.gph,xsize(8)ysize(4)iscale(.8)tit(Alternative dimensions of state capacity)
		gr export "$dir\golden\altdimensions.pdf",as(pdf)replace 
		erase h1.gph
		erase h2.gph		
		
		* Instrument for Lag DV with deeper lags + 2-way FE *
		ivreghdfe vburcap $x $d time (l1vburcap=l3vburcap l4vburcap),a(cowcode)cluster(lid) gmm2s
		
		*****************************************************************
		* Table 2: Interactive fixed effects with cluster-robust errors *
		*****************************************************************
		 use pers-useid,clear
		 qui reghdfe vburcap $d $x,a(cowcode year)vce(cluster lid)
		 lincom $d 
		 qui reghdfe vburcap treat $x,a(cowcode year)vce(cluster lid)
		 lincom treat 
			* With multiple factors *
		 forval i=1/3 {
		 	qui regife vburcap $d $x,a(cowcode year)f(cowcode year,`i') vce(cluster lid)
			lincom $d 
		 	qui regife vburcap ivburcap $d $x,a(cowcode year)f(cowcode year,`i') vce(cluster lid)
			lincom $d 
		 }
		 
		*****************************************
		* Table 2A: Leader-person fixed effects * 
		*****************************************
		 use pers-useid,clear
		 keep if sample==1
		 egen xlid =group(current_leader)
		 sum lid xlid
		 xtset xlid year
		 xtsum v2paind vburcap
		 local x = 0.75*(30^(1/3)) -1 
		 di `x'
		 ivreghdfe vburcap v2paind ld ivdem ivburcap  time ,absorb(cowcode)rob bw(`x')
		 ivreghdfe vburcap v2paind ld ivdem ivburcap  time ,absorb(xlid)rob bw(`x')
 
		************
		*** FECT ***
		************
		use pers-useid,clear
		keep if sample==1
		egen ct= count(year),by(cowcode)
		hist ct
		tab ct 
		qui reghdfe vburcap treat $x,a(cowcode year)vce(cluster lid)
		lincom treat
		qui reghdfe vburcap treat $x if ct>=10,a(cowcode year)vce(cluster lid)
		lincom treat
		keep if ct>=10
		centile v2paind, centile(33.3333 50 66.6667) 
		tab treat1
		gen hitreat = v2paind>.4492157 if v2paind~=.
		tab hitreat
		tab treat1
		
		egen mtreat  =mean(treat1),by(cowcode)
		egen ctag = tag(cowcode) if mtreat~=.
		hist mtreat if ctag==1
		tab mtreat if ctag==1 /* 39 of 89 have no variation in treatment; 50 of 89 units have treatment variation */
		drop mtreat ctag
		egen mtreat  =mean(hitreat),by(cowcode)
		egen ctag = tag(cowcode) if mtreat~=.
		hist mtreat if ctag==1
		tab mtreat if ctag==1 /* 39 of 89 have no variation in treatment; 50 of 89 units have treatment variation */

		xtset cowcode year
		*cap ado uninstall fect
		*net install fect, from(https://raw.githubusercontent.com/xuyiqing/fect_stata/master/) replace
		* 2-way FE *
		xtset cowcode year
		qui fect vburcap,treat(treat1) cov(ld ivdem v2paseats ivburcap) unit(cowcode) time(year) ///
			force(two-way)method(fe)vartype(bootstrap)alpha(0.05)seed(984984)minT0(1)preperiod(-5)offperiod(5)placeboperiod(3) se placeboTest cv
		mat p1 = e(placebo_ATT)
		fect vburcap,treat(treat1) cov(ld ivdem v2paseats ivburcap) unit(cowcode)time(year)degree(3) ///
			force(two-way)method(fe)vartype(bootstrap)alpha(0.05)seed(984984)minT0(1)preperiod(-5)offperiod(5)se equiTest cv    
		mat e1 = e(ATT)
		mat r1 = e(ATTs)
	    mat list e1 
		mat list p1
		mat list r1	 
		gen att=.
		gen n=.
		gen hi=.
		gen lo=.
		gen s=_n-30
		forval i=22(1)32 {
			local n = r1[`i',2]
			local att=r1[`i',3]
			local h=r1[`i',7]
			local l=r1[`i',6]
			qui replace att=`att' if s==`i'-27
			qui replace n=`n' if s==`i'-27
			qui replace hi=`h' if s==`i'-27
			qui replace lo=`l' if s==`i'-27
		}
		twoway  (rarea hi lo s if att~=.,col(gs12)xlab(-5(5)5)yline(0,lcol(red)lpat(solid))) ///
			(line att s if att~=.,lpat(solid)lcol(blue)xtit(Time since the treatment started) ///
			xline(0)legend(off)ytit("Treatment effect of party personalism")ylab(-.2(.1).1)) ///
			(bar n s if att~=.,yaxis(2)yscale(range(0 1000)axis(2))col(gs14)ytit("",axis(2))ylab(0,axis(2)) ///
			saving(h1.gph,replace)tit("Dynamic treatment effects") subtit("median treatment threshold",size(vsmall)))  
			
		* IFE and MC yield similar ATT effect estimates *
		xtset cowcode year
		qui fect vburcap,treat(treat1) cov(ld ivdem v2paseats ivburcap) unit(cowcode) time(year) ///
			force(two-way)method(ife)vartype(bootstrap)alpha(0.05)seed(984984)minT0(3)preperiod(-5)offperiod(5)se placeboTest cv
		mat p2 = e(placebo_ATT)
		qui fect vburcap,treat(treat1) cov(ld ivdem v2paseats ivburcap) unit(cowcode) time(year) ///
			force(two-way)method(ife)vartype(bootstrap)alpha(0.05)seed(984984)minT0(3)preperiod(-5)offperiod(5)se cv
		mat e2 = e(ATT)
		mat r2 = e(ATTs)
		xtset cowcode year
		qui fect vburcap,treat(treat1) cov(ld ivdem v2paseats ivburcap) unit(cowcode) time(year) ///
			force(two-way)method(mc)vartype(bootstrap)alpha(0.05)seed(984984)minT0(3)preperiod(-5)offperiod(5)se placeboTest cv
		mat p3 = e(placebo_ATT)
		qui fect vburcap,treat(treat1) cov(ld ivdem v2paseats ivburcap) unit(cowcode) time(year) ///
			force(two-way)method(mc)vartype(bootstrap)alpha(0.05)seed(984984)minT0(3)preperiod(-5)offperiod(5)se cv
		mat e3 = e(ATT)
		mat r3 = e(ATTs)
		* High treatment threshold *
		xtset cowcode year
		qui fect vburcap,treat(hitreat) cov(ld ivdem v2paseats ivburcap) unit(cowcode) time(year) ///
			force(two-way)method(fe)vartype(bootstrap)alpha(0.05)seed(984984)minT0(3)preperiod(-5)offperiod(5)placeboperiod(3) se placeboTest cv
		mat hp1 = e(placebo_ATT)
		fect vburcap,treat(hitreat) cov(ld ivdem v2paseats ivburcap)unit(cowcode)time(year)degree(3) ///
			force(two-way)method(fe)vartype(bootstrap)alpha(0.05)seed(984984)minT0(3)preperiod(-5)offperiod(5)se equiTest cv  
		mat he1 = e(ATT)
		mat hr1 = e(ATTs)
	    mat list he1 
		mat list hp1
		mat list hr1	 
		forval i=22(1)32 {
			local n = hr1[`i',2]
			local att=hr1[`i',3]
			local h=hr1[`i',7]
			local l=hr1[`i',6]
			qui replace att=`att' if s==`i'-27
			qui replace n=`n' if s==`i'-27
			qui replace hi=`h' if s==`i'-27
			qui replace lo=`l' if s==`i'-27
		}
		twoway (rarea hi lo s if att~=.,col(gs12)xlab(-5(5)5)yline(0,lcol(red)lpat(solid))) ///
			(line att s if att~=.,lpat(solid)lcol(blue)xtit(Time to treatment) ///
			xline(0)legend(off)ytit(Treatment effect)ylab(-.2(.1).1)) ///
			(bar n s if att~=.,yaxis(2)yscale(range(0 1000)axis(2))col(gs14)ytit("",axis(2))ylab(0,axis(2)))
		gen e=.
		replace hi=.
		replace lo=.
		local i = e1[1,1]
		replace e =`i' if s==1
		local i = e1[1,4]
		replace lo = `i' if s==1
		local i = e1[1,5]
		replace hi = `i' if s==1	
		
		local i = he1[1,1]
		replace e =`i' if s==2
		local i = he1[1,4]
		replace lo = `i' if s==2
		local i = he1[1,5]
		replace hi = `i' if s==2
		
		local i = p1[1,1]
		replace e =`i' if s==4
		local i = p1[1,3]
		replace lo = `i' if s==4
		local i = p1[1,4]
		replace hi = `i' if s==4	
		
		local i = hp1[1,1]
		replace e =`i' if s==5
		local i = hp1[1,3]
		replace lo = `i' if s==5
		local i = hp1[1,4]
		replace hi = `i' if s==5	
	
		twoway (rspike hi lo s if s<=5 & s>=1,xscale(range(0.7 5.3))ytit(Effect) ///
			legend(off)xlab(1  `""ATT" "{it:median}" "treatment" "threshold""'  ///
			2 `""ATT" "{it:high}" "treatment" "threshold""' 3 " " ///
			4 `""Placebo test" "{it:median}" "treatment" "threshold""' ///
			5 `""Placebo test" "{it:high}" "treatment" "threshold""')  tit(ATTs and Placebo tests)) ///
			(scatter e s if s<=5 & s>=1,yline(0,lpat(solid)lcol(red))msym(O)xtit(Estimand)saving(h2.gph,replace))
		gr combine h1.gph h2.gph,xsize(10)col(2)
		gr export "$dir\golden\ATTs.pdf",as(pdf)replace 
		
		mat list e1  /* FE, median threshold */
		mat list e2  /* IFE, median threshold */
		mat list e3  /* MC, median threshold */
		mat list he1 /* FE, high threshold */
  
		*******************************************
		*** Kernel regression for visualization ***
		*******************************************
		use pers-useid,clear
		local var = "ld ivdem v2paind v2paseats ivburcap time"
		foreach v of local var {
			egen m_`v'=mean(`v') if sample,by(cowcode)
		}
		reg vburcap ld ivdem v2paseats time $d ivburcap m_* 
		reghdfe vburcap ld ivdem v2paseats time $d ivburcap,a(cowcode)
		reg vburcap ld ivdem v2paseats time $d ivburcap m_*  
		reghdfe vburcap ld ivdem v2paseats time $d ivburcap,a(cowcode)
		krls vburcap ld ivdem v2paseats time $d ivburcap m_*,d(k1)lambda(1.061)ltolerance(2.165)
		sum v2paind if sample==1,detail /* 1 std is 1; 25-75 pctile change is 1.55 */
		replace k1_v2paind=k1_v2paind*1.55
			gen e=.
			gen hi=.
			gen lo=.
			gen n=_n	
		ttest k1_v2paind if sample==1,by(seat50)
			local  m1=r(mu_1) 
			local se1 = r(sd_1)/(sqrt(r(N_1)))
			local  m2=r(mu_2)
			local se2 = r(sd_2)/(sqrt(r(N_2)))
			replace e=`m1' if _n==1
			replace hi = `m1' + 1.95* `se1' if _n==1
			replace lo = `m1' - 1.95* `se1'  if _n==1
			replace e=`m2' if _n==2
			replace hi = `m2' + 1.95*`se2' if _n==2
			replace lo = `m2' - 1.95*`se2' if _n==2				
		twoway (bar e n if n<=2,barwidth(.25)bcol(gs10)ytit(Marginal effect of party personalism) ///
				saving(h1.gph,replace)) (rspike hi lo n if n<=2,ylab(-.1(.02)0)col(gs1)legend(off) ///
				xtit("Legislative seat share, leader's party")yline(0,lcol(red)) ///
				xlab(1 "Less than 50%" 2 ">=50%")xscale(range(.8 2.2)))  	
			drop e hi lo n
		twoway (hist v2paseatshare if v2paseatshare~=.,col(gs12)yscale(range(0 3000)axis(2))yaxis(2)bin(30) ///	
			ylab(none,axis(2))freq ytitle("",axis(2))) (lpolyci k1_v2paind v2paseatshare ///
			if v2paseatshare~=.,bw(25)  lcol(blue*1.2)lpat(solid)col(blue*.25)legend(off) ///
			xtitle("Legislative seat share for leader's party", size(small)) xlab(0(25)100) ///
			ytitle(Marginal effect of party personalism)  yline(0,lcol(red))yscale(alt) ///
			yscale(range(-.08 0)axis(2))ylab(-.1(0.02)0,axis(1))saving(h2.gph,replace))
		gr combine h1.gph h2.gph,xsize(8)ysize(4)  ///
			tit(Party personalism reduces bureaucratic capacity) ///
			subtit(more when executive parties have majorities,size(small))
		gr export "$dir\golden\krls.pdf",as(pdf)replace 
 		twoway (lpolyci k1_v2paind year if type=="parliamentary" & gwf_duration<=25,col(blue*1.1)bw(15)) ///
			(lpolyci  k1_v2paind year if type=="presidential"  & gwf_duration<=25,lpat(solid)col(gs1)bw(15) ///
			legend(lab(2 "Parliamentary")lab(4 "Presidential")order(2 4)pos(6)col(2)) ///
			ylab(-.08(.02).0,axis(1))ytit(Marginal effect )xtit(Year)yscale(range(-.06 0.006)  axis(1)) ///
			yline(0,lcol(red))  tit(New democracies)saving(h1.gph,replace))
		twoway (lpolyci k1_v2paind year if type=="parliamentary" & gwf_duration>25,col(blue*1.1)bw(15)) ///
			(lpolyci k1_v2paind year if type=="presidential"  & gwf_duration>25,lpat(solid)col(gs1)bw(15) ///
			legend(lab(2 "Parliamentary")lab(4 "Presidential")order(2 4)pos(6)col(2)) ///
			ylab(-.08(.02).0)ytit(Marginal effect)xtit(Year)yscale(range(-.06 0.005)alt axis(1)) yline(0,lcol(red)) ///
			tit(Older democracies)saving(h2.gph,replace))
		gr combine h1.gph h2.gph,xsize(8)ysize(4)note("New democracies <=25 years; Older>25 years" , ///
			size(vsmall)pos(6))  tit(Party personalism reduces bureaucratic capacity) ///
			subtit(more in new democracies,size(small)) 					
		gr export "$dir\golden\krls-hetero-effects.pdf",as(pdf)replace 
		erase h1.gph
		erase h2.gph
		ttest k1_v2paind,by(type)
		ttest k1_v2paind if gwf_duration>25,by(type)
		ttest k1_v2paind if gwf_duration<=25,by(type)
		save pers-krls,replace
		
		  * Standard linear interaction specifications *
		use pers-useid,clear
		xi:reghdfe vburcap $x i.seat50*$d,a(cowcode year)vce(cluster lid)
		lincom $d + _IseaX 
		xi:reghdfe vburcap ivburcap $x i.seat50*$d,a(cowcode year)vce(cluster lid)
		lincom $d + _IseaX 
		xi:reghdfe vburcap time time2 $ldv $x i.seat50*$d ,a(cowcode)vce(cluster lid)
		lincom $d + _IseaX 
		
		* Split sample *
		xi:reghdfe vburcap $x $d if seat50==0,a(cowcode year)vce(cluster lid)
		est store split1
		xi:reghdfe vburcap $x $d if seat50==1,a(cowcode year)vce(cluster lid)
		est store split2
		xi:reghdfe vburcap $x ivburcap $d if seat50==0,a(cowcode year)vce(cluster lid)
		est store split3
		xi:reghdfe vburcap $x ivburcap $d if seat50==1,a(cowcode year)vce(cluster lid)
		est store split4
		xi:reghdfe vburcap  $ldv $x  $d if seat50==0,a(cowcode year)vce(cluster lid)
		est store split5
		xi:reghdfe vburcap  $ldv $x  $d if seat50==1,a(cowcode year)vce(cluster lid)
		est store split6
		
		label var $d `""Party    " "personalism""'
		coefplot (split1,msym(S)col(red)lcol(red))(split2,msym(O)col(blue))(split3,msym(O)col(red)) ///
			(split4,msym(S)col(blue))(split5,msym(O)col(red))(split6,msym(O)col(blue)) ///
			,keep($d) ciopts(lcol(1 blue 2 red)) ///
			level(95) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
			xline(0, lpattern(dash))xlab(-0.25(.05)0)legend(lab(2 "2FE, Leg. share <50") lab(4 "2FE, Leg. share >=50") ///
			lab(6 "2FE + inherited capacity level, Leg. share <50") lab(8 "2FE + inherited capacity level, Leg. share >=50")lab(10 "2FE + LDV, <50") ///
			lab(12 "2FE + LDV, Leg. share >=50")pos(7)ring(0))note(95 pct CI,pos(6)size(vsmall)) ///
			title(Split sample results)
		 gr export "$dir\golden\split.pdf",as(pdf)replace 	
		
		
		***********
		* IV-2SLS *
		***********
		use pers-useid,clear
		keep if c>=2
		gen z =.
		forval i = 0.5 0.55 : 1.5 {
			qui replace z = abs(persparty)^(`i')
			qui replace z = z*-1 if persparty<0
			qui ivreghdfe vburcap $x ivburcap time ($d=z),absorb(cowcode)rob bw(3)
			qui local f =  e(widstat)
			di `i'
			di `f'
			di "***" 
		}
		replace z = abs(persparty)^1.2
		replace z=z*-1 if persparty<0
					* Reported model with continous <persparty> variable *
		ivreghdfe vburcap $x ivburcap time $d if sample==1,absorb(cowcode) rob bw(3)  /* OLS */
		ivreghdfe vburcap $x ivburcap time ($d=z) if sample==1,absorb(cowcode) rob bw(3) gmm2s  /* 2SLS */
		est store tsls 
		qui xi:ivreg2 vburcap i.cowcode time $x ivburcap ($d=z) if sample==1,rob bw(3)partial(i.cowcode)gmm2s small
		lincom $d  /* correct syntax yields no warning */
		qui xi:ivreg2 vburcap i.cowcode time $x ivburcap ($d=z) if sample==1,rob bw(3) small gmm2s
		lincom $d   /* incorrect syntax yields warning but the same estimate; and still allows for weakivtest */
		weakivtest
		estout tsls using Table1.tex,cells(b(star  fmt(%9.3f)) se(par fmt(%9.3f))) ///
				stats(N N_clust) style(tex) replace label starlevels(* 0.05) title(\label{tab1})
			
			* Plot 1st-stage residualized relationship *
		qui xi:reg $d z ivburcap i.cowcode time $x if sample==1,cluster(lid)
		lincom  z
		avciplot  z,ciopts(acolor(gs1))rlopts(col(gs1))col(gs10) tit(Residualized first stage: Pre-electoral perssonalism)xtit("Pre-electoral personalism (partial)")ytit("Party personalism (partial)")xlab(-2(2)2) ///
			note("{&beta}=0.17, se=0.04, t=4.4",size(small)ring(-1)pos(7)) 
		gr export "$dir\golden\first-stage-residualized.pdf",as(pdf)replace 			
			
			* F-stats in sub-samples *
		egen mean_ivburcap = mean(ivburcap) if sample==1,by(cowcode)
		gen f =.
		qui xi:ivreg2 vburcap i.cowcode time $x ivburcap ($d=z) if sample==1 & gwf_duration<25,rob bw(3)
		qui weakivtest
		local f =  r(F_eff)  
		qui replace f=`f' if _n==1
			qui xi:ivreg2 vburcap i.cowcode time $x ivburcap ($d=z) if sample==1 & gwf_duration>=25,rob bw(3)
		qui weakivtest
 		local f =  r(F_eff)  
		qui replace f=`f' if _n==2
		qui xi:ivreg2 vburcap i.cowcode time $x ivburcap ($d=z) if sample==1 & mean_iv<.618,rob bw(3)
		qui weakivtest
		local f =  r(F_eff)  
		qui replace f=`f' if _n==4
			qui xi:ivreg2 vburcap i.cowcode time $x ivburcap ($d=z) if sample==1 & mean_iv>=.618,rob bw(3)
		qui weakivtest
		local f =  r(F_eff)   
		qui replace f=`f' if _n==5
		qui xi:ivreg2 vburcap i.cowcode time $x ivburcap ($d=z) if sample==1 & v2x_regime<3,rob bw(3) 
		qui weakivtest
		local f =  r(F_eff)  
		qui replace f=`f' if _n==7
			qui xi:ivreg2 vburcap i.cowcode time $x ivburcap ($d=z) if sample==1 & v2x_regime==3,rob bw(3)
		qui weakivtest
		local f =  r(F_eff)   
		qui replace f=`f' if _n==8
		forval i=1/8 {
			local j = 9+`i'
			qui xi:ivreg2 vburcap i.cowcode time $x ivburcap ($d=z) if sample==1 & e_regionpol!=`i',rob bw(3)
			qui weakivtest
			local f =  r(F_eff)  
			qui replace f=`f' if _n==`j'
		}
		gen m = _n
		list f m in 1/17,clean noobs
		sort m
		graph bar f if m<=17,over(m,label(labgap(*.5)labsize(tiny)) ///
			relabel(1 `""Democracy" "age" "<25 years""' 2 `""Democracy" "age" ">=25 years""' 3 " " ///
			4 `""Low"" state" "capacity""' 5 `""High" "state" "capacity""'  6 " " ///
			7 `""Electoral" "democracy""' 8 `""Liberal" "democracy""' 9 " " ///
			10 `""E. Europe" "post-" "Soviet""' 11 `""Latin" "America""' 12 `""N. Africa" "M. East""' ///
			13 `""Sub-Sah." "Africa""' 14 `""W.Eur." "N. America""'  15 `""East" "Asia""' 16 `""South-East" "Asia""' ///
			17 `""South" "Asia""')) yline(23.1,lcol(red)) yline(37.4,lcol(blue)lpat(dash)) ///
			ytitle(Effective F-statistic) title("Excluded instrument strength, subsamples") scheme(plotplain) ///
			note("Excluded geo-political region                                 ",pos(5)size(vsmall)ring(1)) ///
			text(26 14  "10% bias",size(vsmall)col(red)) text(40 30  "5% bias",size(vsmall)col(blue))
		drop m f    
		gr export "$dir\golden\F-stats.pdf",as(pdf)replace 
		
 		keep if c>=2 /* drop singletons */
		gen opi = l1v2xps_party if year==minyr
		egen ipi = max(opi), by(lid)
		gen olead = v2exl_legitlead if year==minyr
		egen ilead = max(olead),by(lid)
		gen f =.
		gen v =""
		local i = 1
		local var = "v2padisa v2paclient v2pawelf v2pariglef v2xpa_popul v2xpa_illiberal v2palgbt v2pagender v2pawomlab v2paimmig v2paviol v2paminor v2paplur v2paopresp v2papariah v2pavote"
		foreach v of local var {
			qui xi:ivreg2 vburcap i.cowcode time $x ivburcap (`v'=z) if sample==1,cluster(lid) 
			qui di "`v'"
			qui weakivtest
			qui local f =  r(F_eff)  
			qui replace f=`f' if _n==`i'
			qui replace v="`v'" if _n==`i'
			qui local i  = `i' +1
		}

		gen m = _n
		list f m in 1/16,clean noobs
		sort m
		graph bar f if m<=16,over(m,label(labgap(*.5)labsize(tiny)) ///
			relabel(1 `""Internal" "cohesion""' 2  "Clientelism"  3 `""Welfare" "state" "ideology""' ///
			4 `""Right-left" "economic" "ideology""' 5 `""Party" "populism""'  6 `""Party" "illiberalism""' ///
			7 `""LGBTQ" "equality""' 8 `""Gender" "equality""' 9 `""Working" "women""'  ///
			10 "Immigration" 11 `""Reject" "political" "violence""' 12 `""Respect" "minorities""' ///
			13 `""Political" "pluralism""' 14 `""Political" "opponents""'  15 `""Pariah" "status""' ///
			16  `""Vote" "share""' )) ylab(0(20)100) ylin(37.4,lcol(red)) yline(96,lcol(blue)) ///
			ytitle(Effective F-statistic) title("Excluded instrument strength, alternate party dimensions") scheme(plotplain) 
		gr export "$dir\golden\exclusion.pdf",as(pdf)replace 
		
		* Blocking alternative pathways if exclusion restriction violated *
		local var = "v2padisa v2xpa_popul"
		foreach v of local var {
			di "`v'"
			qui ivreghdfe vburcap $x ivburcap ($d=z) time if   `v'~=.,absorb(cowcode)rob bw(3) gmm2s  
			lincom $d
			qui ivreghdfe vburcap $x ivburcap ($d=z) time  `v'  ,absorb(cowcode)rob bw(3) gmm2s  
			lincom $d
		}
		
				*** IV-2SLS covariate adjustment ***
			use pers-useid,clear
			keep if c>=2  /* Drop singletons */
			gen z = abs(persparty)^1.2
		    replace z=z*-1 if persparty<0
			gen n=_n
			gen beta=.
			gen hi=.
			gen lo=.
			gen hi90=.
			gen lo90=.
			gen varname=""
			local i =1
			local var = "l1gdp lpop imr oilrentsgdp intwar civwar civwarany v2xel_elecparl v2xel_elecpres l1v2xps_party l1v2x_civlib l1v2x_clpol l1v2x_clphy l12v2x_jucon l12v2juhcind l1v2x_polyarchy l1v2x_partipdem l1v2xlg_legcon v2x_ex_confidence polarization v2xpa_popul v2paclient v2pawelf v2pariglef v2pasoctie priormil rightpop leftpop" 
			foreach v of local var {
				di "`v'"
				qui ivreghdfe vburcap $x `v' ivburcap time ($d=z) if sample==1,absorb(cowcode) rob bw(3) gmm2s  /* 2SLS */
				qui nlcom _b[v2paind],post
				matrix beta =e(b)  
				local b = beta[1,1]
				qui replace beta=`b' if n==`i'
				matrix var = e(V) 
				local se =var[1,1]
				qui replace hi = `b' + sqrt(`se')*1.96 if n==`i'
				qui replace lo = `b' - sqrt(`se')*1.96 if n==`i'
				qui replace hi90 = `b' + sqrt(`se')*1.65 if n==`i'
				qui replace lo90 = `b' - sqrt(`se')*1.65 if n==`i'
				qui replace varname = "`v'" if n==`i'
				local i = `i' +1
			 }

			label define varlab 1 "GDP per capita" 2 "Population (log)" 3 "Infant mortality rate" ///
				4 "Oil rents" 5 "Int'l war" 6 "Civil war-high" 7 "Civil war-any" 8 "Legislative election" ///
				9 "Executive election" 10 "Party system inst."  11 "Civil liberties" ///
				12 "Political liberties" 13 "Physical integrity rights" 14 "Judicial constraint"   ///
				15 "Judicial indep." 16 "Democracy" 17 "Participatory democracy" 18 "Legislative constraints" ///
				19 "Exec confidence" 20 "Polarization" 21 "Party populism" 22 "Party clientelism"   ///
				23 "Welfare state ideology" 24 "Party econ. ideology" 25 "Party affiliate org's." ///
				26 "Prior military regime" 27 "Right populist" 28 "Left populist",replace
			label values n varlab
				twoway (scatter beta n if n<=28,mcol(blue)yscale(range(-0.01 0.001))yline(-.0699658 ,lcol(gs4)lpat(dash_dot))) ///
				(rspike hi lo n if n<=28,lw(vthin)lcol(blue)) ///
				(rspike hi90 lo90 n if n<=28,lcol(blue)lw(medium)ytitle("{&beta}{sub:Party personalism}", ///
				size(large)height(4))tit(IV-2SLS)   ///
				xtitle(Added covariate,height(33))yline(0,lpat(dash)lcol(red))xlab(1(1)28,valuelabel angle(90))legend(off))
			graph export "$dir\golden\iv-added-covariates.pdf", as(pdf)   replace
	 
		
		
		**************
		** Appendix **
		**************
		use pers-useid,clear
			* HAC errors * 
		 qui ivreghdfe vburcap $x time $d if sample==1,absorb(cowcode) rob bw(3) 
		 lincom $d
		 qui reghdfe vburcap $x time $d if sample==1,absorb(cowcode)vce(cluster lid)
		 lincom $d
		 qui  ivreghdfe vburcap time $ldv  $x $d if sample==1,absorb(cowcode) rob bw(3)   
		 lincom $d
		 qui reghdfe vburcap time $ldv $x $d if sample==1,absorb(cowcode)vce(cluster lid)
		 lincom $d

		* Country-specific time trends with cluster robust se *
		use pers-useid,clear
		gen time3 = time^3
 		 xi:qui reghdfe vburcap $d $x if sample==1,a(cowcode year) cluster(lid)
		 lincom $d 
		 est store time1
 		 xi:qui reghdfe vburcap $d $x time time2 if sample==1,a(cowcode) cluster(lid)
		 lincom $d 
		 est store time2	
 		 xi:qui reghdfe vburcap $d $x time time2 time3 if sample==1,a(cowcode) cluster(lid)
		 lincom $d 
		 est store time3
 		 xi:qui reg vburcap i.cowcode*time $d $x if sample==1,cluster(lid)
		 lincom $d 
		 est store time4
		 xi:qui reg vburcap i.cowcode*time i.cowcode*time2 $d $x if sample==1,cluster(lid)
 		 lincom $d 
		 est store time5		
		 xi:qui reg vburcap i.cowcode*time i.cowcode*time2 $ldv $x $d if sample==1,cluster(lid)
		 lincom $d
		 est store time6
		 xi: qui  reg vburcap i.cowcode*time i.cowcode*time2 i.cowcode*time3 $ldv $x $d if sample==1,cluster(lid)
		  lincom $d
		  est store time7
		 label var $d " "
		coefplot (time1,msym(S)col(blue))(time2,msym(O)col(blue))(time3,msym(T)col(blue))(time4,msym(D)col(blue)) (time5,msym(Oh)col(blue)) ///
				 (time6,msym(s)col(blue)) (time7,msym(t)col(blue)),keep($d)ciopts(lcol(blue)) ///
				level(95) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.12(.04)0)legend(lab(2 "2-way FE" "common") ///
				lab(4 "quadratic time trend" "common") ///
				lab(6 "cubic time trend" "common") ///
				lab(8 "country-specific" "linear time trend") lab(10 "country-specific" "quadratic time trend") ///
				lab(12 "country-specific" "quadratic time trend" "+LDV") lab(14 "country-specific" "cubic time trend" "+LDV") ///
				size(vsmall) pos(7)ring(0))note(95 pct CI,pos(6)size(vsmall)) ///
				title(Modeling calendar time trend)
		gr export "$dir\golden\time.pdf",as(pdf)replace 	
		
    
		* Difference model *
		 xtivreg2 vburcap $d $x if sample==1,fd cluster(lid)
 		 lincom d.$d 
		 est store dif1
		 xtivreg2 vburcap $ldv $d $x if sample==1,fd cluster(lid)
 		 lincom d.$d 
		 est store dif2
		 coefplot (dif1,msym(S)col(blue))(dif2,msym(O)col(blue)),keep(D.$d) ciopts(lcol(blue)) ///
				level(95) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.03(.01)0)legend(lab(2 "No LDV") lab(4 "LDV") ///
				pos(7)ring(0))note(95 pct CI,pos(6)size(vsmall)) ///
				title(First-difference estimator)
		 gr export "$dir\golden\diff.pdf",as(pdf)replace 	
		 xtivreg2 vburcap (l1vburcap=l3vburcap l4vburcap) $x $d if sample==1,fd cluster(cowcode) gmm2s 
		
  		* Sensitivity *
		 qui centile $d if vburcap~=.,centile(50)
		 local  c= r(c_1)
		 gen hipers = $d>`c'
		 qui reghdfe vburcap $x time hipers if sample==1,absorb(cowcode)vce(cluster lid)
		 lincom hipers
		 xi:sensemakr vburcap $x i.cowcode time hipers if sample==1,treat(hipers)benchmark(ld)contour
		 gr export "$dir\golden\sensitivity-contour.pdf",as(pdf)replace 
		 
		* Exclude shorter panels *
		hist c if sample==1,xtit("# of years in panel (unbalanced)")freq bin(28)
		forval i =2(1)15 {
			qui reghdfe vburcap      $d $x time if sample==1 & c>=`i',absorb(cowcode)vce(cluster lid)
			lincom $d
			qui reghdfe vburcap $ldv $d $x time if sample==1 & c>=`i',absorb(cowcode)vce(cluster lid)
			lincom $d
		}
	 
		* Additional covariate adjustment *
		use pers-useid,clear
		tab v2panom_ord
		recode v2panom_ord (4=3)
		gen n=_n
		gen beta=.
		gen hi=.
		gen lo=.
		gen hi90=.
		gen lo90=.
		gen varname=""
		local i =1
		local var = "l1gdp lpop imr oilrentsgdp intwar civwar civwarany v2xel_elecparl v2xel_elecpres l1v2xps_party l1v2x_civlib l1v2x_clpol l1v2x_clphy l12v2x_jucon l12v2juhcind l1v2x_polyarchy l1v2x_partipdem l1v2xlg_legcon v2x_ex_confidence polarization v2xpa_popul v2paclient v2pawelf v2pariglef v2pasoctie priormil rightpop leftpop" 
		foreach v of local var {
			di "`v'"
			qui reghdfe vburcap `v' $x $d time if sample==1,absorb(cowcode)vce(cluster lid)
			qui nlcom _b[v2paind],post
			matrix beta =e(b)  
			local b = beta[1,1]
			qui replace beta=`b' if n==`i'
			matrix var = e(V) 
			local se =var[1,1]
			qui replace hi = `b' + sqrt(`se')*1.96 if n==`i'
			qui replace lo = `b' - sqrt(`se')*1.96 if n==`i'
			qui replace hi90 = `b' + sqrt(`se')*1.65 if n==`i'
			qui replace lo90 = `b' - sqrt(`se')*1.65 if n==`i'
			qui replace varname = "`v'" if n==`i'
			local i = `i' +1
		 }
		label define varlab 1 "GDP per capita" 2 "Population (log)" 3 "Infant mortality rate" ///
			4 "Oil rents" 5 "Int'l war" 6 "Civil war-high" 7 "Civil war-any" 8 "Legislative election" ///
			9 "Executive election" 10 "Party system inst."  11 "Civil liberties" ///
			12 "Political liberties" 13 "Physical integrity rights" 14 "Judicial constraint"   ///
			15 "Judicial indep." 16 "Democracy" 17 "Participatory democracy" 18 "Legislative constraints" ///
			19 "Exec confidence" 20 "Polarization" 21 "Populism" 22 "Party clientelism"   ///
			23 "Party welfare state ideology" 24 "Party econ. ideology" 25 "Party affiliate org's." 26 "Prior military regime" 27 "Right populist" 28 "Left populist" ,replace
		label values n varlab
		twoway (scatter beta n if n<=28,mcol(blue)yscale(range(-.11 .01))yline(-.0759243,lcol(gs4)lpat(dash_dot))) ///
			(rspike hi lo n if n<=28,lw(vthin)lcol(blue)ylab(-0.12(.03)0)) ///
			(rspike hi90 lo90 n if n<=28,lcol(blue)lw(medium)ytitle("{&beta}{sub:Party personalism}", ///
			size(large)height(4))tit(2-way FE) saving(h1.gph,replace) ///
			xtitle(Added covariate,height(33))yline(0,lpat(dash)lcol(red))xlab(1(1)28,valuelabel angle(90))legend(off))
		local i =1
		local var = "l1gdp lpop imr oilrentsgdp intwar civwar civwarany v2xel_elecparl v2xel_elecpres l1v2xps_party l1v2x_civlib l1v2x_clpol l1v2x_clphy l12v2x_jucon l12v2juhcind l1v2x_polyarchy l1v2x_partipdem l1v2xlg_legcon v2x_ex_confidence polarization v2xpa_popul v2paclient v2pawelf v2pariglef v2pasoctie priormil rightpop leftpop" 
		foreach v of local var {
			di "`v'"
			qui reghdfe vburcap $ldv `v' time $x $d if sample==1,absorb(cowcode)vce(cluster lid)
			qui nlcom _b[v2paind],post
			matrix beta =e(b)  
			local b = beta[1,1]
			qui replace beta=`b' if n==`i'
			matrix var = e(V) 
			local se =var[1,1]
			qui replace hi = `b' + sqrt(`se')*1.96 if n==`i'
			qui replace lo = `b' - sqrt(`se')*1.96 if n==`i'
			qui replace hi90 = `b' + sqrt(`se')*1.65 if n==`i'
			qui replace lo90 = `b' - sqrt(`se')*1.65 if n==`i'
			qui replace varname = "`v'" if n==`i'
			local i = `i' +1
		 }
			twoway (scatter beta n if n<=28,mcol(blue)yscale(range(-0.021 0.001))yline(-.0133331,lcol(gs4)lpat(dash_dot))) ///
			(rspike hi lo n if n<=28,lw(vthin)lcol(blue)) ///
			(rspike hi90 lo90 n if n<=28,lcol(blue)lw(medium)ytitle("{&beta}{sub:Party personalism}", ///
			size(large)height(4))tit(FE + LDV) saving(h2.gph,replace) ///
			xtitle(Added covariate,height(33))yline(0,lpat(dash)lcol(red))xlab(1(1)28,valuelabel angle(90))legend(off))
		gr combine h1.gph h2.gph,xsize(10) ysize(4)
		graph export "$dir\golden\added-covariates.pdf", as(pdf)   replace
		erase h1.gph
		erase h2.gph

		* Block alternative dimensions of state capacity via adjustment *
		local i =1
		local var = "vfiscal vterritory hansonsigman_capacity" 
		foreach v of local var {
			di "`v'"
			qui reghdfe vburcap `v' $d $x if sample==1,absorb(cowcode year)vce(cluster lid)
			qui nlcom _b[v2paind],post
			matrix beta =e(b)  
			local b = beta[1,1]
			qui replace beta=`b' if n==`i'
			matrix var = e(V) 
			local se =var[1,1]
			qui replace hi = `b' + sqrt(`se')*1.96 if n==`i'
			qui replace lo = `b' - sqrt(`se')*1.96 if n==`i'
			qui replace hi90 = `b' + sqrt(`se')*1.65 if n==`i'
			qui replace lo90 = `b' - sqrt(`se')*1.65 if n==`i'
			qui replace varname = "`v'" if n==`i'
			local i = `i' +1
		 }
		label define varlab 1 `""Fiscal" "capacity""' 2 `""Territorial" "reach""' 3 `""Hanson-Sigman" "state" "capacity""'  ,replace
		label values n varlab
		twoway (scatter beta n if n<=3,mcol(blue)yline(-.0759243,lcol(red)lpat(dash_dot))) ///
			(rspike hi lo n if n<=3,lw(vthin)lcol(blue)ylab(-0.12(.03)0)xscale(range(0.8 3.2))) ///
			(rspike hi90 lo90 n if n<=3,lcol(blue)lw(medium)ytitle("{&beta}{sub:Party personalism}", ///
			size(large)height(4))tit(2-way FE) saving(h1.gph,replace) ///
			xtitle(Added covariate,height(6))yline(0,lpat(dash)lcol(gs6))xlab(1(1)3,valuelabel)legend(off))
		local i =1
		local var = "vfiscal vterritory hansonsigman_capacity" 
		foreach v of local var {
			di "`v'"
			qui reghdfe vburcap $ldv `v' v2paind $x if sample==1,absorb(cowcode)vce(cluster lid)
			qui nlcom _b[v2paind],post
			matrix beta =e(b)  
			local b = beta[1,1]
			qui replace beta=`b' if n==`i'
			matrix var = e(V) 
			local se =var[1,1]
			qui replace hi = `b' + sqrt(`se')*1.96 if n==`i'
			qui replace lo = `b' - sqrt(`se')*1.96 if n==`i'
			qui replace hi90 = `b' + sqrt(`se')*1.65 if n==`i'
			qui replace lo90 = `b' - sqrt(`se')*1.65 if n==`i'
			qui replace varname = "`v'" if n==`i'
			local i = `i' +1
		 }
			twoway (scatter beta n if n<=3,mcol(blue)yline(-.013333,lcol(red)lpat(dash_dot))) ///
			(rspike hi lo n if n<=3,lw(vthin)lcol(blue) xscale(range(0.8 3.2))) ///
			(rspike hi90 lo90 n if n<=3,lcol(blue)lw(medium)ytitle("{&beta}{sub:Party personalism}", ///
			size(large)height(4))tit(FE + lag DVs) saving(h2.gph,replace) ///
			xtitle(Added covariate,height(6))yline(0,lpat(dash)lcol(gs6))xlab(1(1)3,valuelabel)legend(off))
		gr combine h1.gph h2.gph,xsize(8) ysize(4) ///
			tit(Blocking causal pathways by adjusting for alternative state capacity dimensions)
		graph export "$dir\golden\block-alt-dimensions.pdf", as(pdf)   replace
		erase h1.gph
		erase h2.gph
		
		* Other aggregation of vbur index *
		use pers-useid,clear
		local var = "v2clrspct  v2stcritrecadm   v2x_pubcorr   v2cltrnslw  v2strenadm"
		foreach v of local var {
			qui sum `v'
			qui gen p`v'=`v'+abs(r(min))
		}
 		gen vbur_add =  v2clrspct + v2stcritrecadm +  v2x_pubcorr +  v2cltrnslw + v2strenadm
		gen vbur_mult = pv2clrspct * pv2stcritrecadm *  pv2x_pubcorr *  pv2cltrnslw * pv2strenadm
		pca v2clrspct  v2stcritrecadm    v2x_pubcorr   v2cltrnslw   v2strenadm
		predict vbur_pca
		qui sum vbur_pca if sample==1
		replace vbur_pca=(vbur_pca-r(mean))/r(sd)
		qui sum vbur_add if sample==1
		replace vbur_add=(vbur_add+r(mean))/r(sd)		 
		qui sum vbur_mult if sample==1
		replace vbur_mult=(vbur_mult-r(mean))/r(sd)	
		sum vburcap vbur_mult vbur_add vbur_pca if sample==1
		corr vburcap vbur_mult vbur_add vbur_pca if sample==1
		qui reghdfe vburcap  ivburcap $d $x time if sample==1,absorb(cowcode)vce(cluster lid)
		lincom $d
		local i =1
		local var = "vbur_pca vbur_mult vbur_add"
		foreach v of local var {
			xtset cowcode year
			gen o`v'=ll.`v' if year==minyr
			egen i`v'=max(o`v'),by(lid)
			qui reghdfe `v'  i`v' $d $x time if sample==1,absorb(cowcode)vce(cluster lid)
			est store alt`i'
			lincom $d
			local i = `i'+1
		}
		 coefplot (alt1,msym(S)col(blue))(alt2,msym(O)col(blue)) (alt3,msym(D)col(blue)),keep($d) ciopts(lcol(blue)) ///
				level(95) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.1(.05)0)legend(lab(2 "PCA") lab(4 "Multiplicative") lab(6 "Additive") ///
				pos(7)ring(0))note(95 pct CI,pos(6)size(vsmall)) ///
				title(Alternative Impartial state admin aggregations)
		graph export "$dir\golden\alt-aggregation.pdf", as(pdf)   replace

		* 4-item test of bureaucratic capacity that drop renumeration *
		use pers-useid,clear
		gen z = abs(persparty)^1.2
		replace z=z*-1 if persparty<0
		gen ovburcap4=l1vburcap4 if year==minyr
		egen ivburcap4=max(ovburcap4),by(lid)
		reghdfe vburcap4 $d $x time if sample==1,absorb(cowcode)vce(cluster lid)
		est store i41
		reghdfe vburcap4 l1vburcap4 l2vburcap4 $d $x time if sample==1,absorb(cowcode)vce(cluster lid)
		est store i42
		ivreghdfe vburcap4  ivburcap4 time $x $d if sample==1,absorb(cowcode) cluster(lid)
		est store i43
		label var $d " "
		coefplot (i41,msym(S)col(blue))(i42,msym(O)col(blue))(i43,msym(T)col(blue)) ///
				,keep($d)ciopts(lcol(blue)) ///
				level(95) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.12(.04)0)legend(lab(2 "FE") ///
				lab(4 "FE + LDV") lab(6 "FE + Y{sub:t=0}"))note(95 pct CI,pos(6)size(vsmall)) ///
				title(4-item measure of State capacity)
		gr export "$dir\golden\4-item-tests.pdf",as(pdf)replace 

		*********************************
		* Footnote on one-way FE models *  -0.08 estimate
		*********************************
		reghdfe vburcap $d $x,a(cowcode year)cluster(lid)
		est store re1
		reghdfe vburcap $d $x,a(year)cluster(lid)
		est store re2
		reghdfe vburcap $d $x time,a(cowcode)cluster(lid)
		est store re3
		xtreg vburcap $d $x time,cluster(cowcode)
		est store re4
		coefplot (re1,msym(S)col(blue))(re2,msym(O)col(blue))(re3,msym(T)col(blue))(re4,msym(D)col(blue)) ///
				,keep($d)ciopts(lcol(blue)) ///
				level(95) grid(glcolor(gs16)) xtitle(`=ustrunescape("\u03B2\u0302")'{sub:Party personalism}) ///
				xline(0, lpattern(dash))xlab(-0.3(.1)0)legend(lab(2 "2-way FE") lab(4 "year FE") ///
				lab(6 "country FE + time trend") lab(8 "country RE + time trend")pos(7)ring(0))note(95 pct CI,pos(6)size(vsmall)) ///
				title(Comparing  FE and RE estimators)
		gr export "$dir\golden\re-tests.pdf",as(pdf)replace 	
		
		***********************************************************************
		* Appendix F: Causal mediation analysis for leader control over party *
		***********************************************************************
		*** Other party features correlations ***
		use pers-useid,clear
		keep if sample==1 & persparty~=.
		gen leadcontrol =  v2panom_ord==0 if v2panom_ord~=.
		gen leadfund = v2pafunds_6
		alpha v2palocoff v2paactcom,std item gen(localstrength)
		qui sum localstrength 
		replace localstrength= (localstrength+abs(r(min)))
		qui sum localstrength
		replace localstrength=localstrength/r(max)
		gen z = abs(persparty)^1.2
		replace z=z*-1 if persparty<0
		local var = "v2pawelf v2pariglef leadfund leadcontrol"
		foreach v of local var {
			qui sum `v'
			qui replace `v'=(`v'-r(mean))/r(sd)
		}
		sum leadcontrol v2pawelf v2pariglef leadfund localstrength 
		twoway lpolyci v2pawelf v2paind if sample==1,yline(0,lpat(solid)) ///
			saving(h1.gph,replace)bw(1)ylab(1 "1 StDev" 0.5 "0.5 StDev" 0 "Mean" -.5 "-0.5 StDev" -1 "-1 StDev" ) ///
			ytit(Party welfare state ideology)xtit(Party personalism)legend(off)
		twoway lpolyci v2pawelf z if sample==1,yline(0,lpat(solid)) ///
			saving(h3.gph,replace)bw(1)ylab(1 "1 StDev" 0.5 "0.5 StDev" 0 "Mean" -.5 "-0.5 StDev" -1 "-1 StDev" ) ///
			ytit(Party welfare state ideology)xtit(Party personalism Instrument)legend(off) 		
		twoway lpolyci v2pariglef v2paind if sample==1,yline(0,lpat(solid)) ///
			saving(h2.gph,replace)bw(1)ylab(1 "1 StDev" 0.5 "0.5 StDev" 0 "Mean" -.5 "-0.5 StDev" -1 "-1 StDev" ) ///
			ytit(Party L-R ideology)xtit(Party personalism)legend(off)
		twoway lpolyci v2pariglef z if sample==1,yline(0,lpat(solid)) ///
			saving(h4.gph,replace)bw(1)ylab(1 "1 StDev" 0.5 "0.5 StDev" 0 "Mean" -.5 "-0.5 StDev" -1 "-1 StDev" ) ///
			ytit(Party L-R ideology)xtit(Party personalism Instrument)legend(off) 		
		gr combine h1.gph h2.gph h3.gph h4.gph,col(2)tit("                 Welfare state ideology                                          Left-right ideology")
		
		
		twoway lpolyci leadfund v2paind if sample==1,yline(0,lpat(solid))tit(Leader funds party)  ///
			saving(h1.gph,replace)bw(1)xlab(-2(1)2)ylab(0.5 "0.5 StDev" 0 "Mean" -.5 "-0.5 StDev")  ///
			ytit(Leader funds party)xtit(Party personalism)legend(off)
		twoway lpolyci leadfund v2paind if sample==1,yline(0,lpat(solid))tit(Leader controls nominations)  ///
			saving(h2.gph,replace)bw(1)xlab(-2(1)2)ylab(0.5 "0.5 StDev" 0 "Mean" -.5 "-0.5 StDev")  ///
			ytit(Leader controls nominations)xtit(Party personalism)legend(off)
		gr combine h1.gph h2.gph,col(2) 
		gr export "$dir\golden\leader-control.pdf",as(pdf)replace 

		qui centile v2paind if vburcap~=.,centile(50)
		local  c= r(c_1)
		gen hipers = v2paind>`c'
		ivreghdfe leadfund v2paind if sample==1,bw(3)rob  
		est store ld1
		ivreghdfe leadfund v2paind if sample==1,a(cowcode)bw(3)rob
		est store ld2
		ivreghdfe leadfund v2paind ivdem ld time if sample==1,a(cowcode)bw(3)rob
		est store ld3
 		ivreghdfe leadfund (v2paind=z) ivdem ld time if sample==1,a(cowcode)bw(3)rob
		est store ld4
		ivreghdfe leadcontrol v2paind if sample==1,bw(3)rob  
		est store ld5
		ivreghdfe leadcontrol v2paind if sample==1,a(cowcode)bw(3)rob
		est store ld6
		ivreghdfe leadcontrol v2paind ivdem ld time if sample==1,a(cowcode)bw(3)rob
		est store ld7
		ivreghdfe leadcontrol (v2paind=z) ivdem ld time if sample==1,a(cowcode)bw(3)rob
		est store ld8
		estout ld* using TableF1.tex,cells(b(star  fmt(%9.3f)) se(par fmt(%9.3f))) ///
				stats(N N_clust) style(tex) replace label starlevels(* 0.05) title(\label{tabF1})
			
		twoway (line v2paind year if country=="Hungary",sort saving(h1.gph,replace)) ///
			(line v2paind year if country=="United States",sort) ///
			(line v2paind year if country=="Venezuela",sort xlab(1992(4)2020)xtit(Year) ///
			ytit("Ruling party personalism")legend(lab(1 "Hungary")lab(2 "United States") ///
			lab(3 "Venezuela")pos(6)col(3)ring(1)size(vsmall))tit(Expert-coded ruling party personalism))
		twoway (line persparty year if country=="Hungary",sort ) ///
			(line persparty year if country=="United States",sort saving(h2.gph,replace)) ///
			(line persparty year if country=="Venezuela",sort xlab(1992(4)2020)xtit(Year) ///
			ytit("Pre-election party personalism")legend(lab(1 "Hungary")lab(2 "United States") ///
			lab(3 "Venezuela")pos(6)col(3)ring(1)size(vsmall))tit(Pre-election party personalism))
		gr combine h1.gph h2.gph,xsize(7)
 		gr export "$dir\golden\party-personalism-examples.pdf",as(pdf)replace 
		
		xi:reghdfe vburcap $x leadcontrol,a(cowcode year)vce(cluster lid)
		est store m1
		xi:reghdfe vburcap $x leadfund,a(cowcode year)vce(cluster lid)	
		est store m2
		xi:reghdfe vburcap ivburcap $x leadcontrol,a(cowcode year)vce(cluster lid)
		est store m3
		xi:reghdfe vburcap ivburcap $x leadfund,a(cowcode year)vce(cluster lid)
		est store m4
		xi:reghdfe vburcap l1vburcap l2vburcap $x leadcontrol,a(cowcode year)vce(cluster lid)
		est store m5
		xi:reghdfe vburcap l1vburcap l2vburcap $x leadfund,a(cowcode year)vce(cluster lid) 
		est store m6
		estout m1 m2 m3 m4 m5 m6 using TableF2.tex,cells(b(star  fmt(%9.3f)) se(par fmt(%9.3f))) ///
				stats(N N_clust) style(tex) replace label starlevels(* 0.05) title(\label{tabF2})		
				
		alpha leadfund leadcontrol,std item gen(lcontrol)
		replace lcontrol = (lcontrol+.46)^(1/2)
		hist lcontrol
		xi:reghdfe vburcap          v2paind $x if lcontrol~=.,a(cowcode year)vce(cluster lid)
		est store med1
		xi:reghdfe vburcap lcontrol v2paind $x if lcontrol~=.,a(cowcode year)vce(cluster lid)
		est store med2
		xi:reghdfe vburcap          v2paind ivburcap $x if lcontrol~=.,a(cowcode year)vce(cluster lid)
		est store med3
		xi:reghdfe vburcap lcontrol v2paind ivburcap $x if lcontrol~=.,a(cowcode year)vce(cluster lid)
		est store med4
		xi:reghdfe vburcap          v2paind l1vburcap l2vburcap $x if lcontrol~=.,a(cowcode year)vce(cluster lid)
		est store med5
		xi:reghdfe vburcap lcontrol v2paind l1vburcap l2vburcap $x if lcontrol~=.,a(cowcode year)vce(cluster lid)
		est store med6

		estout med* using TableF3.tex,cells(b(star  fmt(%9.3f)) se(par fmt(%9.3f))) ///
				stats(N N_clust) style(tex) replace label starlevels(* 0.05) title(\label{tabF3})	
				
		local var = "lcontrol v2paind ivburcap ivdem ld v2paseatshare time"
		foreach v of local var {
			qui egen m_`v'=mean(`v') if lcontrol~=.,by(cowcode)
		}
		sum lcontrol v2paind ivburcap ivdem ld v2paseatshare time m_* if lcontrol~=.
		xi:reghdfe vburcap lcontrol v2paind ivburcap $x time if lcontrol~=.,a(cowcode)vce(cluster lid)
		reg  vburcap lcontrol v2paind ivburcap $x time m_* if lcontrol~=.,vce(cluster lid)
		
		local x = "ivburcap ivdem ld v2paseatshare time m_*"
		medeff (regress lcontrol v2paind `x') (regress vburcap v2paind lcontrol `x'),  ///
			mediate(lcontrol) treat(v2paind) sims(1000) seed($seed)
		drop m_*

		
		***********************************************************************************
		* Appendix G: Political experience of ministerial appointments in Benin and Ghana *
		***********************************************************************************
		use pers-use,clear
		sort country year
		save, replace
		use "$dir\Sigman_MinisterData_forIRT.dta", clear
		gen year = appt_year
		sort country year
		merge country year using pers-use,
		tab _merge if pol_exp~=.
		tab country if pol_exp~=.
		gen ovburcap = l1vburcap if year==minyr
		egen ivburcap = max(ovburcap),by(lid)
		tab pres if _merge==1
		drop if pol_exp==.
		gen benin=country=="Benin"
		gen time =year-1990

		sum pol_exp v2paind persparty 
		tab pres if v2paind==.
		tab  year pres if persparty==.  /* Not Jan 1 GWF democracies */
		replace v2paind = -.745 if pres=="Soglo"

		twoway lpolyci pol_exp v2paind,legend(off)bw(.5)xtit(Ruling party personalism)tit(Prior political experience) ///
			ytit(Probability appointee has {bf:prior political experience},size(small))saving(h1.gph,replace)ylab(.2(.2)1)
		reg pol_exp v2paind time,cluster(pres)
		reg pol_exp v2paind ld ivdem time,cluster(pres)
		reg pol_exp v2paind ld ivdem benin time,cluster(pres)
		reghdfe pol_exp v2paind ld ivdem time,a(region)cluster(pres)
		probit pol_exp v2paind ld ivdem benin time,cluster(pres)
		margins,dydx(v2paind)
		est store p1

		twoway lpolyci mpbefore v2paind,legend(off)bw(.5)xtit(Ruling party personalism)tit(Prior MP) ///
			ytit(Probability appointeed was {bf:prior MP},size(small))saving(h2.gph,replace)ylab(.2(.2)1)
		reg mpbefore v2paind time,cluster(pres)
		reg mpbefore v2paind ld ivdem time,cluster(pres)
		reg mpbefore v2paind ld ivdem benin time,cluster(pres)
		reghdfe mpbefore v2paind ld ivdem time,a(region)cluster(pres)
		probit mpbefore v2paind ld ivdem benin time,cluster(pres)
		margins,dydx(v2paind)
		est store p2
		
		twoway lpolyci partymember v2paind,legend(off)bw(.5)xtit(Ruling party personalism)tit(Prior party member) ///
			ytit(Probability appointee was a {bf:party member},size(small))saving(h3.gph,replace)ylab(.2(.2)1)
		reg partymember v2paind time,cluster(pres)
		reg partymember v2paind ld ivdem time,cluster(pres)
		reg partymember v2paind ld ivdem benin time,cluster(pres)
		reghdfe partymember v2paind ld ivdem time,a(region)cluster(pres)
		probit partymember v2paind ld ivdem benin time,cluster(pres)
		margins,dydx(v2paind)
		est store p3
		
		twoway lpolyci exp_match2 v2paind,legend(off)bw(.5)xtit(Ruling party personalism)tit(Prio professional experience) ///
			ytit(Probability appointee has {bf:professional experience},size(small))saving(h4.gph,replace)ylab(.2(.2)1)
		reg exp_match2 v2paind time,cluster(pres)
		reg exp_match2 v2paind ld ivdem time,cluster(pres)
		reg exp_match2 v2paind ld ivdem benin time,cluster(pres)
		reghdfe exp_match2 v2paind ld ivdem time,a(region)cluster(pres)
		probit exp_match2 v2paind ld ivdem benin time,cluster(pres)
		margins,dydx(v2paind)
		est store p4
		
		estout p1 p2 p3 p4 using TableG1.tex,cells(b(star  fmt(%9.3f)) se(par fmt(%9.3f))) ///
			stats(N N_clust) style(tex) replace label starlevels(* 0.05 ) title(\label{tabG1})
			
		gr combine h1.gph h2.gph h3.gph h4.gph,col(4)xsize(10)
		gr export "$dir\golden\minister-appt.pdf",as(pdf)replace 	
	
		use pers-use,clear
		sort cowcode year
		save, replace
		
		**********************************************
		* Appendix H: WhoGov minister purge analysis *
		**********************************************
		import excel "WhoGov_within_V2.0.xlsx",firstrow clear
		destring year,replace
		keep if year>=1989

		gen country = country_name
		gen cowcode =.
		qui do cowcodes
		replace cowcode = 484 if country_name=="Congo - Brazzaville"
		replace cowcode = 490 if country_name=="Congo - Kinshasa"
		replace cowcode = 437 if country_name=="Côte d'Ivoire"
		replace cowcode = 316 if country_name=="Czechia"
		tab country if cowcode==.
		drop if cowcode==.
		drop country
		rename country_name whogov_country 
		sort cowcode year
		merge cowcode year using pers-use
		tab _merge
		 sort whogov_country year
		*merge whogov_country year using leadermatch 
		*tab _merge leadermatch,m

		tab whogov_country if _merge==1  /* dictatorships */
		drop if _merge==1
		tab year

		egen nameid = group( whogov_country name position)
		egen minnameyear = min(year),by(nameid)
		gen duration = 1 if year ==minnameyear & nameid~=.
		sort nameid year
		replace duration = duration[_n-1]+1 if duration==. & nameid==nameid[_n-1]
		gen d1 =duration
		gen d2=duration^2
		gen d3=duration^3
		egen maxd = max(duration),by(nameid)
		gen fail = maxd==duration
		replace deadyear="2021" if deadyear=="A (2021)" |   deadyear=="A (2022)"  | deadyear=="A(2022)" | deadyear=="A (2020)"
		destring deadyear,replace
		recode fail (1=0) if deadyear==year  /* replaced due to natural death */

		tab class
		gen s1  = (class=="Director of Government Agency" | class=="Deputy Director of Government Agency") 
		gen s2  = (class=="Director of Government Agency" | class=="Deputy Director of Government Agency")  & core==0
		qui sum v2paind if s1==1
		replace v2paind = (v2paind + abs(r(mean)))/r(sd)
		qui sum v2xpa_popul if s1==1
		replace v2xpa_popul = (v2xpa_popul - abs(r(mean)))/r(sd)
		sum v2paind v2xpa_popul if s1==1
		gen election = v2xel_elecparl==1 |  v2xel_elecpres==1
		gen ovburcap=l1vburcap if year==minyr
		egen ivburcap=max(ovburcap),by(lid)
		egen lmin =min(year),by(lid)
		gen leaderduration  =1 if year==lmin
		forval i = 1(1)10 {
			local j=`i'+1
			replace leaderduration =`j' if year==lmin+`i'
		}
		sum leaderduration year if s1==1
		gen lnleaderduration = ln(leaderduration)
		gen time  =year-1990
		gen leadcontrol =  v2panom_ord==0 if v2panom_ord~=.
		gen leadfund = v2pafunds_6
		egen xlid=group(cowcode current_leader)
		sort cowcode year
		save who-use,replace


		* Check different link functions *
		qui reg fail v2paind d1 d2 d3 if s2==1, cluster(nameid)
		lincom v2paind
		qui probit fail v2paind d1 d2 d3 if s2==1, cluster(nameid)
		margins,dydx(v2paind)
		qui logit fail v2paind d1 d2 d3 if s2==1, cluster(nameid)
		margins,dydx(v2paind)
		qui krls fail v2paind d1 d2 d3 if s2==1, lambda(.3547)
		qui local e = e(Output)[1,1]
		qui local se = e(Output)[1,2]
		di `e' `se'

		* Models reported in Table H-1 *
		reg fail v2paind d1 d2 d3 if s2==1, cluster(nameid)
		est store a1
		reghdfe fail v2paind d1 d2 d3 if s2==1,a(cowcode)cluster(nameid)
		est store a2
		reghdfe fail v2paind d1 d2 d3 time if s2==1,a(cowcode)cluster(nameid)
		est store a3
		reghdfe fail v2paind d1 d2 d3 time ld ivdem ivburcap election if s2==1,a(cowcode)cluster(nameid)
		est store a4
		reghdfe fail v2paind d1 d2 d3 time ld ivdem ivburcap election if s2==1,a(cowcode portfolio_1)cluster(nameid)
		est store a5
		reghdfe fail v2paind d1 d2 d3 time ld election if s2==1,a(xlid)cluster(nameid)
		est store a6
		estout a1 a2 a3 a4 a5 a6 using TableH1.tex,cells(b(star  fmt(%9.3f)) se(par fmt(%9.3f))) ///
			stats(N N_clust) style(tex) replace label starlevels(* 0.05) title(\label{tabH1})
			
		* Test nonbureaucratic, political appointees *
		reghdfe fail v2paind d1 d2 d3 if s1==0,a(cowcode)cluster(nameid)
		reghdfe fail v2paind d1 d2 d3 time if s1==0,a(cowcode)cluster(nameid)
		reghdfe fail v2paind d1 d2 d3 time ld ivdem ivburcap election if s1==0,a(cowcode)cluster(nameid)
		reghdfe fail v2paind d1 d2 d3 time ld ivdem ivburcap election if s1==0,a(cowcode portfolio_1)cluster(nameid)
		reghdfe fail v2paind d1 d2 d3 time ld election if s1==0,a(xlid)cluster(nameid)

		* Check when including core appointments among agency heads *
		tab class core if s1==1
		reg fail v2paind d1 d2 d3 if s1==1, cluster(nameid)
		reghdfe fail v2paind d1 d2 d3 if s1==1,a(cowcode)cluster(nameid)
 		reghdfe fail v2paind d1 d2 d3 time if s1==1,a(cowcode)cluster(nameid)
 		reghdfe fail v2paind d1 d2 d3 time ld ivdem ivburcap election if s1==1,a(cowcode)cluster(nameid)
 		reghdfe fail v2paind d1 d2 d3 time ld ivdem ivburcap election if s1==1,a(cowcode portfolio_1)cluster(nameid)
 		reghdfe fail v2paind d1 d2 d3 time ld election if s1==1,a(xlid)cluster(nameid)
		
		* Check IFE *
		regife  fail v2paind d1 d2 d3 ld ivdem ivburcap election if s2==1,a(cowcode year)ife(cowcode year,1)vce(cluster nameid)

		* Check CRE probit *
		xthybrid fail v2paind d1 d2 d3 time ld ivdem ivburcap election if s2==1,cluster(cowcode)family(ordinal)link(probit) cre p

		* Check mechanisms *
		reghdfe fail leadcontrol d1 d2 d3 time ld ivdem ivburcap election if s2==1,a(cowcode)cluster(nameid)
		reghdfe fail leadfund    d1 d2 d3 time ld ivdem ivburcap election if s2==1,a(cowcode)cluster(nameid)

		xi:interflex fail v2paind lnleaderduration d1 d2 d3 ivburcap ld ivdem election if s2==1,fe(cowcode year)cluster(nameid)nbin(3)
		mat list r(estBin)
		mat e = r(estBin)
		gen e=.
		gen h=.
		gen l=.
		gen n=_n
		gen g =.
		forval i =1(1)3 {
			replace e=e[`i',2] if n==`i'
			replace h =e[`i',5] if n==`i'
			replace l=e[`i',4] if n==`i'
			replace g =e[`i',1] if n==`i'
		}
		twoway (rspike h l g if n<=3,lpat(solid))  (scatter e g if n<=3,msym(O)legend(off)xtit(Leader time in power) ///
			xscale(range(-.2 1.8))xlab(0 "First year" 0.69 "2nd year" 1.6094 "5th year")yline(0,lcol(red)) ///
			ytit(Marginal effect of Party personalism)tit("Party personalism increases bureaucratic purge in leader's first year"))
		xi:interflex fail v2paind lnleaderduration d1 d2 d3 time ivburcap ld ivdem election if s2==1,fe(cowcode)cluster(nameid)type(kernel)bw(0.3252)
		mat e = r(margeff)
		forval i =1(1)50 {
			qui replace e=e[`i',2] if n==`i'
			qui replace h =e[`i',5] if n==`i'
			qui replace l=e[`i',4] if n==`i'
			qui replace g =e[`i',1] if n==`i'
		}
		twoway (rarea h l g if n<=50,col(gs14))  (line e g if n<=50,lcol(gs1)lpat(solid)legend(off)xtit(Leader time in power) ///
			xscale(range(0 2.35))xlab(0 "First year" 0.69 "2nd year" 1.6094 "5th year" 2.302585 "10th year")yline(0,lcol(red)) ///
			ytit(Marginal effect of Party personalism)tit("Party personalism increases bureaucratic purge in leader's first year"))
		gr export "$dir\golden\bureaucrat-purge.pdf",as(pdf)replace 


		log close
		

erase .png
erase .pdf
erase h1.gph
erase h2.gph
erase h3.gph
erase h4.gph
erase master.dta
erase pers-krls.dta
erase pers-temp.dta
erase pers-use.dta
erase pers-useid.dta
erase vdem-parties-merge.dta
erase who-use.dta
